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:
