News Category

Java convert image to PDF

2021-06-01 07:45:14 Written by  support iceblue
Rate this item
(0 votes)

We have demonstrated how to use Spire.PDF for java to convert PDF to image. This article will show you how to convert image to PDF in Java applications.

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfImage;

public class imageToPDF {
    public static void main(String[] args) throws Exception {

        //Create a PDF document
        PdfDocument pdf = new PdfDocument();
        //Add a new page
        PdfPageBase page = pdf.getPages().add();

        //Load the image
        PdfImage image = PdfImage.fromFile("logo.jpg");

        double widthFitRate = image.getPhysicalDimension().getWidth() / page.getCanvas().getClientSize().getWidth();
        double heightFitRate = image.getPhysicalDimension().getHeight() / page.getCanvas().getClientSize().getHeight();
        double fitRate = Math.max(widthFitRate, heightFitRate);

        //get the picture width and height
        double fitWidth = image.getPhysicalDimension().getWidth() / fitRate;
        double fitHeight = image.getPhysicalDimension().getHeight() / fitRate;

        //Draw image
        page.getCanvas().drawImage(image, 0, 30, fitWidth, fitHeight);

        // Save document to file
        pdf.saveToFile("output/ToPDF.pdf");
        pdf.close();

    }
}

Output:

Java convert image to PDF

Additional Info

  • tutorial_title:
Last modified on Thursday, 02 September 2021 06:25