Android 多张图片转PDF文件

功能:相机、相册选取单张图片,合并转PDF文件,过大图片可全部展示

效果图:

在这里插入图片描述

实现组件:iText组件

代码:

 implementation 'com.itextpdf:itextg:5.5.10'
 private static String pdfUrl;
    //画布最宽:500
    private static int MAX_WIDTH = 550;
    //画布最高:750
    private static int MAX_HEIGHT = 750;
    
    public static String imgOfPdf(String filepath, String imgUrl) {
        try {
            //图片list集合
            ArrayList<String> imageUrllist = new ArrayList<String>();
            String[] imgUrls = imgUrl.split(",");
            for (int i=0; i<imgUrls.length; i++) {
                imageUrllist.add(imgUrls[i]);
            }
            //输出pdf文件路径
            Log.d("测试输出pdf文件路径", filepath);
            pdfUrl = filepath;
            //生成pdf
            File file = imgToPdf(imageUrllist, pdfUrl);
            file.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return pdfUrl;
    }
    public static File imgToPdf(ArrayList<String> sources, String target) {
        //创建文件并设置文档页边距
        Document document  = new Document(PageSize.A4, 20, 20, 20, 20);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(target);
            PdfWriter.getInstance(document , fos);

            //打开文件
            document .open();

            // 添加PDF文档的某些信息,比如作者,主题等等
			//document.addTitle("鲁班移动");
			//document.addAuthor("作者:zhengtai.li@kuwo.cn");
		 	//document.addSubject("主题:企业信息");
			// 写入一段文字
 			// document.add(new Paragraph("Test! Test! Test! Test! Test! Test!"));

     
       for (int i = 0; i < sources.size(); i++) {
                //获取原图片的宽高
                Image image = Image.getInstance(sources.get(i));
                float imageHeight = image.getScaledHeight();
                float imageWidth = image.getScaledWidth();

                // 获取缩放比例
                int percent = 100;
                //如果原图宽度大于原图高度,则使用宽度来计算缩放比例,否则按高度来计算缩放比较。
                //例:原图高1500,宽1000,则使用画布高度和原图高度来计算缩放比例(750/1500*100=50%)
                if (imageWidth >= imageHeight) {
                    //小于画布宽度的图片不用缩放
                    if (imageWidth > MAX_WIDTH) {
                        percent = Math.round(MAX_WIDTH / imageWidth * 100) - 3;
                    }
                } else {
                    //小于画布高度的图片不用缩放
                    if (imageHeight > MAX_HEIGHT) {
                        percent = Math.round(MAX_HEIGHT / imageHeight * 100) - 3;
                    }
                }

                // 设置图片比例,表示是原来图像的比例(原图越大,percent的值越小);
                image.scalePercent(percent);

                //图片居中
                image.setAlignment(Image.MIDDLE);

                //新建一页添加图片
                document.newPage();
                document.add(image);
            }
        } catch (Exception e) {
            Log.d("{}图片合成失败:{}", target+ e.getMessage()+ e);
            return null;
        }finally {
            //关闭文档
            document.close();
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Log.d("关闭文档失败。。。","");
            }
        }

        File outputPdfFile = new File(target);
        if (!outputPdfFile.exists()) {
            outputPdfFile.deleteOnExit();
            return null;
        }
        return outputPdfFile;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用以下代码将PDF文件换为图片: ```java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.pdf.PdfRenderer; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); File pdfFile = new File("path/to/pdf/file.pdf"); try { // create a new PdfRenderer object PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY)); // get the number of pages in the PDF file final int pageCount = renderer.getPageCount(); // get the first page of the PDF file PdfRenderer.Page page = renderer.openPage(0); // create a new bitmap object Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(), Bitmap.Config.ARGB_8888); // create a new canvas object Canvas canvas = new Canvas(bitmap); // set the background color of the canvas object canvas.drawColor(Color.WHITE); // render the PDF page into the canvas object page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); // set the bitmap image to the ImageView imageView.setImageBitmap(bitmap); // close the page object page.close(); // close the renderer object renderer.close(); // save the bitmap image as a JPEG file FileOutputStream out = new FileOutputStream("path/to/output/file.jpg"); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意替换代码中的文件路径。此代码将PDF文件的第一页换为图片,并将其显示在ImageView中,然后将其保存为JPEG文件。你可以更改代码以换多页PDF文件或更改输出图像的格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值