无法使用 PDFBox 将 TIFF 图像添加到 PDF 中

问题描述 投票:0回答:1

我在尝试使用 PDFBox 3.0.3 创建包含多个 TIF 图像的 PDF 时遇到了一些问题。 :( 我尝试了几种不同的方法,但到目前为止都没有奏效。我得到的页面基本上是空白的,每页上都有一条黑线。 :(

尝试1

PDDocument document = new PDDocument();
for (int i=0;i<5;i++)
{
String sTIFFpath = sRootDir+i;
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
PDImageXObject image = PDImageXObject.createFromFile(sTIFFpath, document);
contentStream.drawImage(image, 0, 0);
contentStream.close();
}

创建图像的行生成异常。然而,图像对象被生成并重新调整。查看生成的 PDF,我看到基本上是空白页面,其中只有一个空行。

这是异常的堆栈跟踪

2024-09-29 19:49:26,490 DEBUG PDImageXObject - Reading as TIFF failed, setting fileType to PNG
java.io.IOException: First image in tiff is not a single tile/strip
    at org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory.extractFromTiff(CCITTFactory.java:439)
    at org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory.createFromRandomAccessImpl(CCITTFactory.java:215)
    at org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory.createFromFile(CCITTFactory.java:195)
    at org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory.createFromFile(CCITTFactory.java:173)
    at org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject.createFromFileByExtension(PDImageXObject.java:236)
    at org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject.createFromFile(PDImageXObject.java:192)

为了解决该异常,我用以下两行替换了生成图像的行:

BufferedImage biTiff = ImageIO.read(new File(sTIFFpath));
PDImageXObject image = CCITTFactory.createFromImage(document, biTiff);

这给我的程序执行增加了相当多的时间,但消除了异常。但是生成的 PDF 是相同的。 :(

经过大量搜索,我发现了另一种方法。我再次用以下代码替换了创建图像的单行:

ImageInputStream is = ImageIO.createImageInputStream(new File(sTIFFpath));
Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
ImageReader reader = (ImageReader) iterator.next();
iterator = null;
reader.setInput(is);
int iImgCnt = reader.getNumImages(true);
for (int i=0; i < iImgCnt; i++)
{
BufferedImage biTiff = reader.read(i);
PDImageXObject img = CCITTFactory.createFromImage(document, biTiff);
//  PDImageXObject img = LosslessFactory.createFromImage(document, biTiff);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
page = new PDPage();
document.addPage(page);
}

没有例外,但结果是一样的。

java pdfbox tiff
1个回答
0
投票

更改您的尝试 1 代码:

contentStream.drawImage(image, 0, 0);

致:

// Resize image to fit page
contentStream.drawImage(image, 0, 0, page.getMediaBox().getWidth(), page.getMediaBox().getHeight());
© www.soinside.com 2019 - 2024. All rights reserved.