How can I convert a PNG file to PDF using java? [closed]
Asked Answered
O

5

10

Are there any open source libraries that I can use?

Oculomotor answered 2/12, 2011 at 19:59 Comment(0)
B
17

itext may help you. you don't really convert a png to pdf but create a pdf with a png in it. simple example:

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();
Bula answered 2/12, 2011 at 20:4 Comment(0)
C
6

An example which rotates the page, if landscape mode fits better

/**
 * Converts arbitrary image file to PDF
 * https://mcmap.net/q/1044389/-how-can-i-convert-a-png-file-to-pdf-using-java-closed
 * @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 https://mcmap.net/q/264796/-how-do-i-scale-one-rectangle-to-the-maximum-size-possible-within-another-rectangle
        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();
    }
}

Inside pom.xml, one of free iText forks, if you are not already using iText

<dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.0.1</version>
</dependency>
Conte answered 21/3, 2017 at 20:24 Comment(3)
with this approach how does one write more than one image on the same documentMcwherter
I believe I ended up combining up the resulting PDFs in another service.Conte
Is it not hard way of doing it? would you mind sharing the codeMcwherter
A
5

Use iText to convert jpg/png/gif to pdf with following code. It's work perfect.

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();
    }
  }
}
Appetitive answered 19/11, 2019 at 4:56 Comment(0)
C
1

for reading javax.imageio.ImageIO for writing pdf itext: http://itextpdf.com

Chimpanzee answered 2/12, 2011 at 20:4 Comment(0)
M
0

For simplicity modern web pages carying PNG or JPEG can be command line converted to single or multiple page PDFs.

By placing an image at default width or height, or set to be kept at any scale it only takes a few lines of command line text to output a PDF. Very easy to template in a simple notepad or complex IDE.

For the conversion chrome -headless can be faster for one page than releasing the enter key, it takes a bit longer for 4000 images.

Other libraries can be used for more complex operations as a post process. However Chrome will only produce an exceptionally good default media page , unless adding extra CSS.

so echo the following from console or other editor

<HTML>
<image src="01.jpg" width="100%" />
<image src="02.jpg" width="100%" />
</HTML>

Run your Java shell equivalent of

"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --print-to-pdf="C:\Data\out.pdf" C:/Data/htm.htm

Result

enter image description here

Masonite answered 16/1, 2023 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.