Java:使用 PDFBox 库从图像创建 PDF 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22358478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:13:30  来源:igfitidea点击:

Java: Create PDF pages from images using PDFBox library

javapdfjava-7pdfbox

提问by Daniel Ruf

I need to convert images (mainly JPEG) directly to PDF pages for a PDF document.
It may be that the images differ in size.

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

Each PDF page should have the exact dimensions as the images.
So each page only contains the image in full resolution.

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

How can this be achieved, that a page is set to the dimensions of the image/content?
Because I saw PDF files with different page sizes and orientations but how can this be done with PDFBox?

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

采纳答案by Daniel Ruf

I have solved this with the following code:

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

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

For completeness the code from the current PDFBox examples for PDFBox 2+ API (https://svn.apache.org/repos/asf/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/AddImageToPDF.java)

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

/*
 * 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>" );
    }
}

回答by Kishan Solanki

Not with PDFBox,

不适用于 PDFBox,

but you need to add itextpdfdependency in your project:

但是你需要在你的项目中添加itextpdf依赖项:

Here is the function to convert an image to pdf in JAVA

这是在JAVA中将图像转换为pdf的功能

void convertImageToPDF(BufferedImage bufferedImage) {
    writeImage(bufferedImage,
            "path-to-image-xyz/xyz.jpg", "JPG");

    String outputFile = "finalOutput.pdf";
    File root = new File("/path-to-image-xyz/");
    ArrayList<String> files = new ArrayList<>();
    files.add("xyz.jpg");

    Document document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(new File(root, outputFile)));
        document.open();
        for (String f : files) {
            document.newPage();
            com.itextpdf.text.Image image = com.itextpdf.text.Image
                    .getInstance(new File(root, f).getAbsolutePath());
            image.setAbsolutePosition(0, 0);
            image.setBorderWidth(0);
            image.scaleAbsolute(500f, 850f);
            image.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
            float x = (PageSize.A4.getWidth() - image.getScaledWidth()) / 2;
            float y = (PageSize.A4.getHeight() - image.getScaledHeight()) / 2;
            image.setAbsolutePosition(x, y);
            document.add(image);
            document.add(image);
            document.add(image);
        }
        document.close();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
    }
}


public void writeImage(BufferedImage img, String fileLocation,
                              String extension) {
    try {
        File outputFile = new File(fileLocation);
        ImageIO.write(img, extension, outputFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

By this function, if your image is at D:/project/xyz.jpglocation, then your output pdf file would be at D:/project/finalOutput.pdf

通过此功能,如果您的图像在D:/project/xyz.jpg某个位置,那么您的输出 pdf 文件将位于D:/project/finalOutput.pdf