gpt4 book ai didi

android - 如何将图像转换为 PDF?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:54:59 24 4
gpt4 key购买 nike

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

    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();
}
}

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

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

有什么解决办法吗?

已更新

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

实际图像是 enter image description here

最佳答案

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

实现 '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();

关于android - 如何将图像转换为 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36305362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com