dd12
dd12

Reputation: 11

iText7 adding SVG into PdfDocument and aligning SVG image properly within the PDF

I am able to add the SVG image in PDF using the below code but alignment of image is going for a toss. I would like to keep image in a confined area (let's say 300 x 300 size always). If image is bigger, it should shrink/compress and fit into this size. How can we achieve this.

PdfDocument doc = null;
try {
    doc = new PdfDocument(new PdfWriter(new FileOutputStream(new File("D:\\test.pdf")),
            new WriterProperties().setCompressionLevel(0)));
    doc.addNewPage();

    URL svgUrl = null;
    String svgPath = "...svgPathHere";

    try {
        svgUrl = new URL(svgPath);
    } catch(MalformedURLException mue) {
        System.out.println("Exception caught" + mue.getMessage() );
    }

    if (svgUrl == null){
        try {
            svgUrl = new File(svgPath).toURI().toURL();
        } catch(Throwable th) {
            System.out.println("Exception caught" + th.getMessage());
        }
    }

    SvgConverter.drawOnDocument(svgUrl.openStream(), doc, 1, 100, 200); // 100 and 200 are x and y coordinate of the location to draw at
    doc.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Adding to the same above question, drawOnDocument() method of SvgConverter provides us the control to postion our svg through x and y cordinates. Is there a better way to handle postioning? (like Top-left, Top-right)

Upvotes: 1

Views: 1433

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12312

In your code you are dealing with quite low-level API. While your task is quite simple and low-level API is still sufficient here, with higher-level layout API you can achieve the goal much faster.

To start with, you can reuse your code to create a PdfDocument and define the URL for the SVG image:

PdfDocument doc = new PdfDocument(new PdfWriter(new FileOutputStream(new File("D:\\test.pdf")),
        new WriterProperties().setCompressionLevel(0)));
String svgPath = "...svgPathHere";

Then, instead of drawing the SVG image on a page immediately, you can convert it into an Image object from layout API which you can configure: scale to fit particular dimensions, set fixed position (left bottom point) and so on:

Image image = SvgConverter.convertToImage(new FileInputStream(svgPath), doc);
image.setFixedPosition(100, 200);
image.scaleToFit(300, 300);

To tie everything together, create high-level Document object and add your image there. Don't forget to close the Document instance. You don't need to close your original PdfDocument anymore:

Document layoutDoc = new Document(doc);
layoutDoc.add(image);

layoutDoc.close();

Upvotes: 2

Related Questions