Convert SVG to PDF and Add a SVG Image to PDF in Java

Start from Spire.PDF for Java 3.9.6, it supports converting SVG to PDF with several rows of codes, and adding a SVG image to PDF efficiently. This article will show you how to do it.

Convert SVG to PDF

Spire.PDF for Java offers the loadFromSvg method to load a SVG sample directly and then convert it to PDF file using the saveToFile method.

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class SVGToPDF {
    public static void main(String[] args) {
        //Load a SVG sample
        PdfDocument doc = new PdfDocument();
        doc.loadFromSvg("C:\\Users\\Test1\\Desktop\\logo.svg");
        //Save to PDF file
        doc.saveToFile("output/ToPDF.pdf", FileFormat.PDF);
    }
}

Output

Convert SVG to PDF and Add a SVG Image to PDF in Java

Add a SVG image to PDF

In addition to converting SVG to PDF, Spire.PDF for Java supports adding a SVG image to PDF. You can set the position and size of the image during the process.

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import java.awt.*;
import java.awt.geom.Point2D;

public class AddSVGImagetoPDF {
    public static void main(String[] args) {
        //Load a SVG sample
        PdfDocument doc1 = new PdfDocument();
        doc1.loadFromSvg("C:\\Users\\Test1\\Desktop\\logo.svg");
        //Load a PDF sample
        PdfDocument doc2 = new PdfDocument();
        doc2.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");
        //Set the position and size of the image
        doc2.getPages().get(0).getCanvas().drawTemplate(doc1.getPages().get(0).createTemplate(),
                new Point2D.Float(100,150), new Dimension(200,200) );
        //Save to PDF file
        doc2.saveToFile("output/AddSVGImagetoPDF.pdf", FileFormat.PDF);
        doc1.close();
        doc2.close();
    }
}

Output

Convert SVG to PDF and Add a SVG Image to PDF in Java