怎么把Image转换成PDF? [英] How to convert Image to PDF?

查看:167
本文介绍了怎么把Image转换成PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要将图像转换为PDF的应用程序.我尝试了一些方法,但是问题是,该PDF中的图像大小非常小.我需要解决此问题的解决方案.我也在寻找将多个图像转换为单个PDF文档. 我将发布我尝试过的代码.

I am developing an application where I need to convert an Image to PDF. I tried something, but the issue is, Image size in that PDF is very very small. I need solution to fix this. Also I am looking for converting multiple Images into single PDF document. I will post the code which I tried.

    public void convertPDF(byte[] path)
{
 String FILE = "mnt/sdcard/FirstPdf.pdf";
    Document document=new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();

        try {
            image=Image.getInstance(path);
            document.add(new Paragraph("My Heading"));
            document.add(image);
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

当我将位图转换为字节数组时,我正在压缩图像,我猜这就是原因.如果不压缩图像,则无法将位图转换为字节数组.

When I convert Bitmap to Byte array, I am compressing the image and I guess, that's the reason. Without compressing the image, I am unable to convert Bitmap to Byte Array.

 ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
        byte[] byteArray=stream.toByteArray();
        convertPDF(byteArray);

有什么解决办法吗?

已更新

在这里,我已经实现了@Burak Cakir在答案中建议的答案.但是现在我在PDF中得到了更大的图像.为了更好地理解,请找到下面的图像.

Here I have implemented the answer which suggested by @Burak Cakir in the answer. But now I am getting larger image in PDF. For better understanding, Please find the images below.

实际的图像是

推荐答案

我建议您使用 pdf库.这是gradle依赖项:

I would suggest you to use iText pdf library. Here is the gradle dependency:

implementation 'com.itextpdf:itextg:5.5.10'

 Document document = new Document();

 String directoryPath = android.os.Environment.getExternalStorageDirectory().toString();

 PdfWriter.getInstance(document, new FileOutputStream(directoryPath + "/example.pdf")); //  Change pdf's name.

 document.open();

 Image image = Image.getInstance(directoryPath + "/" + "example.jpg");  // Change image's name and extension.

 float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
               - document.rightMargin() - 0) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
 image.scalePercent(scaler);
 image.setAlignment(Image.ALIGN_CENTER | Image.ALIGN_TOP); 

 document.add(image);
 document.close();

这篇关于怎么把Image转换成PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆