PDFBox:根据输入PDF绘制不同位置和大小的图像

时间:2015-03-10 04:53:03

标签: java image pdf pdfbox

我已使用Nick Russler提供的代码将图像添加到文档中,以回答此处的另一个问题https://stackoverflow.com/a/20618152/4652269

/**
 * Draw an image to the specified coordinates onto a single page. <br>
 * Also scaled the image with the specified factor.
 * 
 * @author Nick Russler
 * @param document PDF document the image should be written to.
 * @param pdfpage Page number of the page in which the image should be written to.
 * @param x X coordinate on the page where the left bottom corner of the image should be located. Regard that 0 is the left bottom of the pdf page.
 * @param y Y coordinate on the page where the left bottom corner of the image should be located.
 * @param scale Factor used to resize the image.
 * @param imageFilePath Filepath of the image that is written to the PDF.
 * @throws IOException
 */
public static void addImageToPage(PDDocument document, int pdfpage, int x, int y, float scale, String imageFilePath) throws IOException {   
    // Convert the image to TYPE_4BYTE_ABGR so PDFBox won't throw exceptions (e.g. for transparent png's).
    BufferedImage tmp_image = ImageIO.read(new File(imageFilePath));
    BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);        
    image.createGraphics().drawRenderedImage(tmp_image, null);

    PDXObjectImage ximage = new PDPixelMap(document, image);

    PDPage page = (PDPage)document.getDocumentCatalog().getAllPages().get(pdfpage);

    PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
    contentStream.drawXObject(ximage, x, y, ximage.getWidth()*scale, ximage.getHeight()*scale);
    contentStream.close();
}

基本上,图像是通过XObjectImage添加到PDF页面的,但是我发现相同的代码会根据所使用的PDF获得不同的结果。我的猜测似乎有一些规模或变化,但我无法找到或纠正这个。

页面报告(来自MediaBox PDRectangle)它(大约)600x800(页面单位)。但是当我放置我的500px图像时,它会根据使用的PDF以不同的方式显示。在一个PDF中它出现在页面的宽度(这是一个生成的PDF - 即文本和对象等)。在另一张PDF中,图像大约是宽度的一半到三分之一(此PDF是PDF页面上扫描的A4 TIF图像 - 图像大约是1700x2300px - 与我的图像中出现的缩小比例对齐),以及最后在PDF页面上的另一个TIF图像,我添加的图像也旋转了90度。

我很明显需要添加或修改变换 - 页面有默认值 - 或者记住最后使用的变换,我想要的是1:1比例和0度旋转,但我不需要&# 39;不知道怎么做?

我已经阅读过有关Matrix和AffineTransformations的内容 - 但它对我来说并没有多大意义。

有没有办法将文档或drawXObject设置为旋转0度的1:1比例?

1 个答案:

答案 0 :(得分:1)

  

我的猜测似乎有一些规模或变化,但我无法找到或纠正这个。

是的,你的代码

PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

按原样在页面的内容流列表的末尾添加新的内容流。这意味着它从以前最后一个流结束的图形状态开始。

某些工具会创建内容流,这些内容流的结束状态与开始时相同,但这不是PDF规范强加的要求。

要确保您的添加内容以默认图形状态开头,您必须将现有内容包含在一对运算符 q ... Q 中,以保存和恢复图形状态。

幸运的是,如果您使用不同的PDPageContentStream构造函数(具有三个布尔参数的构造函数),并且使用true作为附加参数的值,PDFBox已经为您执行此操作:

PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);