通过 Android PDFDocument 生成的 PDF 尺寸太大。在使用 pdfbox 时,它会在输出中剪切图像

PDF size too large generating through Android PDFDocument. And while using pdfbox it is cutting image in output

我正在使用 android pdf 文档库将图像转换为 pdf,但生成的 pdf 尺寸非常大。

PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo =new 
PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();                            
PdfDocument.Page  page = document.startPage(pageInfo);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), 
bitmap.getHeight(),false);                        

Canvas canvas = page.getCanvas();
canvas.drawBitmap(scaledBitmap, 0f, 0f, null);
document.finishPage(page);

document.writeTo(new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/"+newPDFNameSingle));
document.close();

这里是 apache pdf 框实现,但它在输出 pdf 中切割图像

PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);

PDPageContentStream contentStream = new PDPageContentStream(document, page);
InputStream inputStream = new FileInputStream(tempFile);
PDImageXObject ximage = JPEGFactory.createFromStream(document,inputStream);

contentStream.drawImage(ximage, 20, 20);
contentStream.close();

document.save(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/"+newPDFNameSingle);
                            document.close();

如何实现常规大小的pdf生成?我的图像大小为 100 kb,但 pdf 生成 1 mb 文件。

在您的 android pdf 文档库代码中,您将页面大小设置为图像高度和宽度值

PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();                            

并在原点绘制图像:

canvas.drawBitmap(scaledBitmap, 0f, 0f, null);

您可以在 PDFBox 代码中执行相同的操作:

PDDocument document = new PDDocument();

PDImageXObject ximage = JPEGFactory.createFromStream(document,imageResource);

PDPage page = new PDPage(new PDRectangle(ximage.getWidth(), ximage.getHeight()));
document.addPage(page);

PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(ximage, 0, 0);
contentStream.close();

(DrawImage 测试 testDrawImageToFitPage)

或者,如评论中所述,您可以在绘制图像之前设置当前变换矩阵以将其缩小以适合页面。