【问题标题】:Java: Create PDF pages from images using PDFBox 1 libraryJava:使用 PDFBox 1 库从图像创建 PDF 页面
【发布时间】:2014-04-16 23:57:26
【问题描述】:

我需要将图像(主要是 JPEG)直接转换为 PDF 文档的 PDF 页面。
可能是图片大小不同。

每个 PDF 页面都应具有与图像相同的尺寸。
所以每个页面只包含全分辨率的图像。

如何将页面设置为图像/内容的尺寸?
因为我看到了不同页面大小和方向的 PDF 文件,但是如何使用 PDFBox 来完成呢?

【问题讨论】:

  • 也许这可以给你一个想法:stackoverflow.com/questions/10466569/…
  • 好吧,它不是 PDFBox,我认为我们必须在 PDFBox 中的图像之前创建页面,而且 Gnostice PDFOne 不是开源或免费的
  • 好吧,不是PDFBox,但使用PDFBox你也可以制作缓冲图像,这就是为什么我说“给你一个想法”,让我看看我能不能做点什么
  • 对,我应该使用 PDPage(PDRectangle size) 并使用实际的图像尺寸吗?这是正确/最佳的解决方案吗?
  • 是的,这就是我想说的 C: 只是没找到单词

标签: java pdf java-7 pdfbox


【解决方案1】:

注意(Valentin Waeselynck 的评论:从 PDFBox 2+ 开始,您现在可以使用 PDImageXObject.createFromFile 或 PDImageXObject.createFromFile 或 JPEGFactory.createFromStream。请注意,LosslessFactory.createFromImage 的空间会少得多-高效。见:https://pdfbox.apache.org/2.0/migration.html#working-with-images

PDFBox 1 解决方案:

我已经用以下代码解决了这个问题:

PDDocument document = new PDDocument();
InputStream in = new FileInputStream(someImage);
BufferedImage bimg = ImageIO.read(in);
float width = bimg.getWidth();
float height = bimg.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page); 
PDXObjectImage img = new PDJpeg(document, new FileInputStream(someImage));
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
in.close();

document.save("test.pdf");
document.close();

为了完整起见,PDFBox 2+ API (https://svn.apache.org/repos/asf/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/AddImageToPDF.java) 的当前 PDFBox 示例中的代码

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pdfbox.examples.pdmodel;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

/**
 * This is an example that creates a reads a document and adds an image to it..
 *
 * The example is taken from the pdf file format specification.
 *
 * @author Ben Litchfield
 */
public class AddImageToPDF
{
    /**
     * Add an image to an existing PDF document.
     *
     * @param inputFile The input PDF to add the image to.
     * @param imagePath The filename of the image to put in the PDF.
     * @param outputFile The file to write to the pdf to.
     *
     * @throws IOException If there is an error writing the data.
     */
    public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
            throws IOException
    {
        try (PDDocument doc = PDDocument.load(new File(inputFile)))
        {
            //we will add the image to the first page.
            PDPage page = doc.getPage(0);

            // createFromFile is the easiest way with an image file
            // if you already have the image in a BufferedImage, 
            // call LosslessFactory.createFromImage() instead
            PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);

            try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true))
            {
                // contentStream.drawImage(ximage, 20, 20 );
                // better method inspired by http://stackoverflow.com/a/22318681/535646
                // reduce this value if the image is too large
                float scale = 1f;
                contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);
            }
            doc.save(outputFile);
        }
    }

    /**
     * This will load a PDF document and add a single image on it.
     * <br>
     * see usage() for commandline
     *
     * @param args Command line arguments.
     */
    public static void main(String[] args) throws IOException
    {
        AddImageToPDF app = new AddImageToPDF();
        if( args.length != 3 )
        {
            app.usage();
        }
        else
        {
            app.createPDFFromImage( args[0], args[1], args[2] );
        }
    }

    /**
     * This will print out a message telling how to use this example.
     */
    private void usage()
    {
        System.err.println( "usage: " + this.getClass().getName() + " <input-pdf> <image> <output-pdf>" );
    }
}

【讨论】:

  • PDFBox 示例中的类似情况:svn.apache.org/repos/asf/pdfbox/trunk/examples/src/main/java/… 它使用更新的 PDFBox 2+ API
  • 您评论了一个 6 年前的答案/解决方案。在库的最后一个主要版本中,情况可能发生了变化。一个简单的“这不起作用”也不是很有帮助。
  • 注意:从 PDFBox 2+ 开始,您现在将使用 PDImageXObject.createFromFile 或 PDImageXObject.createFromFile 或 JPEGFactory.createFromStream。请注意, LosslessFactory.createFromImage 的空间效率会低得多。见:pdfbox.apache.org/2.0/migration.html#working-with-images
  • 很有趣,谢谢。我已经更新了问题标题以反映它是关于 PDFBox 1 的,我将添加一个包含链接的部分并将您链接到那里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 2012-05-15
  • 2018-01-15
  • 2013-07-15
  • 2015-02-01
相关资源
最近更新 更多