簡體   English   中英

如何使用 java 將 PNG 文件轉換為 PDF? [關閉]

[英]How can I convert a PNG file to PDF using java? [closed]

有沒有我可以使用的開源庫?

itext可能會幫助你。 您並沒有真正將 png 轉換為 pdf,而是創建一個包含 png 的 pdf。 簡單的例子:

Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("C:/test.pdf"));
document.open();
Image image = Image.getInstance(getClass().getResource("/logo.png"));
document.add(image);
document.close();

如果橫向模式更適合,則旋轉頁面的示例

/**
 * Converts arbitrary image file to PDF
 * http://stackoverflow.com/a/42937466/241986
 * @param imageFile contents of JPEG or PNG file
 * @param outputStream stream to write out pdf, always closed after this method execution.
 * @throws IOException when there' an actual exception or image is not valid
 */
public static void imageToPdf(byte[] imageFile, OutputStream outputStream) throws IOException {
    try {
        Image image;
        try {
            image = Image.getInstance(imageFile);
        } catch (BadElementException bee) {
            throw new IOException(bee);
        }

        //See http://stackoverflow.com/questions/1373035/how-do-i-scale-one-rectangle-to-the-maximum-size-possible-within-another-rectang
        Rectangle A4 = PageSize.A4;

        float scalePortrait = Math.min(A4.getWidth() / image.getWidth(),
                A4.getHeight() / image.getHeight());

        float scaleLandscape = Math.min(A4.getHeight() / image.getWidth(),
                A4.getWidth() / image.getHeight());

        // We try to occupy as much space as possible
        // Sportrait = (w*scalePortrait) * (h*scalePortrait)
        // Slandscape = (w*scaleLandscape) * (h*scaleLandscape)

        // therefore the bigger area is where we have bigger scale
        boolean isLandscape = scaleLandscape > scalePortrait;

        float w;
        float h;
        if (isLandscape) {
            A4 = A4.rotate();
            w = image.getWidth() * scaleLandscape;
            h = image.getHeight() * scaleLandscape;
        } else {
            w = image.getWidth() * scalePortrait;
            h = image.getHeight() * scalePortrait;
        }

        Document document = new Document(A4, 10, 10, 10, 10);

        try {
            PdfWriter.getInstance(document, outputStream);
        } catch (DocumentException e) {
            throw new IOException(e);
        }
        document.open();
        try {
            image.scaleAbsolute(w, h);
            float posH = (A4.getHeight() - h) / 2;
            float posW = (A4.getWidth() - w) / 2;

            image.setAbsolutePosition(posW, posH);
            image.setBorder(Image.NO_BORDER);
            image.setBorderWidth(0);

            try {
                document.newPage();
                document.add(image);
            } catch (DocumentException de) {
                throw new IOException(de);
            }
        } finally {
            document.close();
        }
    } finally {
        outputStream.close();
    }
}

在 pom.xml 中,免費的 iText 分支之一,如果您還沒有使用 iText

<dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.0.1</version>
</dependency>

使用iText使用以下代碼將 jpg/png/gif 轉換為 pdf。 它的工作完美。

import java.io.FileOutputStream;
//com.lowagie...   old version
//com.itextpdf...  recent version
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;

public class ImageToPDF {
  public static void main(String ... args) {
    Document document = new Document();
    String input = "c:/temp/capture.png"; // .gif and .jpg are ok too!
    String output = "c:/temp/capture.pdf";
    try {
      FileOutputStream fos = new FileOutputStream(output);
      PdfWriter writer = PdfWriter.getInstance(document, fos);
      writer.open();
      document.open();
      document.add(Image.getInstance(input));
      document.close();
      writer.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

用於閱讀 javax.imageio.ImageIO 以編寫 pdf itext: http ://itextpdf.com

您可以使用以下代碼使用 IronPdf Java 輕松轉換一張或多張圖像。 您可以訪問他們的網站以獲取更多信息,例如“格式化 Pdfs ”和“操作 Pdfs ”。

import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
    // Reference to the directory containing the images that we desire to convert
    Path imageDirectory = Paths.get("assets/images");

// Create an empty List to contain Paths to images from the directory.
    List<Path> imageFiles = new ArrayList<>();

// Use a DirectoryStream to populate the List with paths for each image in the directory
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(imageDirectory, "*.{png,jpg}")) {
        for (Path entry : stream) {
            imageFiles.add(entry);
        }

        // Render all targeted images as PDF content and save them together in one PDF document.
        PdfDocument.fromImage(imageFiles).saveAs(Paths.get("assets/composit e.pdf"));
    } catch (IOException exception) {
        throw new RuntimeException(String.format("Error converting images to PDF from directory: %s: %s",
                imageDirectory,
                exception.getMessage()),
                exception);
        }
    }
}

為簡單起見,可以將帶有 PNG 或 JPEG 的現代 web 頁面通過命令行轉換為單頁或多頁 PDF。

通過以默認寬度或高度放置圖像,或設置為保持任何比例,只需幾行命令行文本即可 output PDF。非常容易在簡單的記事本或復雜的 IDE 中制作模板。

對於轉換 chrome -headless 一頁比釋放回車鍵更快,4000 張圖像需要更長的時間。

其他庫可用於更復雜的操作作為后處理。 然而 Chrome 只會產生一個非常好的默認媒體頁面,除非添加額外的 CSS。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM