Inserting a SVG image file in a PDF file using aspose.pdf for java

Hi,

I am trying to insert a SVG image file to a PDF document using addImage method of class “com.aspose.pdf.facades.PdfFileMend”. The code fails when I try to insert an SVG. No error shown. The image file does not get inserted. It works for jpgs, or pngs though. Can you provide a sample code to make inserting a SVG image file in a PDF document at specified coordinates possible?

@Batrinux

Thank you for contacting support.

I would like to share with you that an SVG image appears invisible if it is bigger than the page size. So, please try setting the page size by using the code below:

page.getPageInfo().setWidth(800);
page.getPageInfo().setHeight(800);

or you may set page orientation as Landscape with the code:

page.getPageInfo().setLandscape(true);

I hope the inserted image will not appear invisible anymore. However, the contents are added in flow layout (Top-Left to Bottom-Right) and in case you need to place image at specific location, you need to use absolute positioning. Aspose.Pdf includes a class named ImageStamp which offers the feature to place image object at absolute position inside the PDF document. But this class only supports Raster images, so in order to place SVG images, you need to convert SVG image to Raster image using Aspose.Imaging for Java and then place raster image inside PDF file.

You are using facades approach to insert an SVG image. Whereas, Aspose.Pdf.Facades is an old model and soon it is going to be obsolete, which is why we always recommend to use DOM (Document Object Model) approach which is more flexible and enhanced.

A sample code for inserting an SVG image in a PDF file using DOM approach, is as under:

// Instantiate Document object
Document doc = new Document();

// add page to pages collection of PDF file
com.aspose.pdf.Page page = doc.getPages().add();

// Create an image instance
com.aspose.pdf.Image img = new com.aspose.pdf.Image();

// Set image type as SVG
img.setFileType(com.aspose.pdf.ImageFileType.Svg);

// Path for source file
img.setFile("D:\\test.svg");

// Set left margin for image instance
img.getMargin().setLeft(10);

// Set Top margin for image instance
img.getMargin().setTop(10);

// add image to PDF file
page.getParagraphs().add(img);

//Set page properties
page.getPageInfo().setWidth(800);
page.getPageInfo().setHeight(800);
page.getPageInfo().setLandscape(true);

// save resultant PDF file
doc.save("D:\\Test.pdf");

I hope this will be helpful. Please let us know if you need any further assistance.