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












1















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)










share|improve this question





























    1















    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)










    share|improve this question



























      1












      1








      1








      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)










      share|improve this question
















      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)







      image pdf svg pdf-generation itext7






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 21 at 19:51









      Alexey Subach

      4,79972143




      4,79972143










      asked Jan 18 at 19:59









      dd12dd12

      61




      61
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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();





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54260676%2fitext7-adding-svg-into-pdfdocument-and-aligning-svg-image-properly-within-the-pd%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            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();





            share|improve this answer




























              0














              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();





              share|improve this answer


























                0












                0








                0







                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();





                share|improve this answer













                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();






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 21 at 19:49









                Alexey SubachAlexey Subach

                4,79972143




                4,79972143






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54260676%2fitext7-adding-svg-into-pdfdocument-and-aligning-svg-image-properly-within-the-pd%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Homophylophilia

                    Updating UILabel text programmatically using a function

                    Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage