I am no expert at this, but looking at some old code, try:
svg.getRoot().setAttributeNS(null, "viewbox", "0 0 " + width + " " + 
fullHeight);

From: Aaron Weber <aaron.webe...@gmail.com>
Sent: Friday, 31 March 2023 9:57 AM
To: batik-users@xmlgraphics.apache.org
Subject: Generate SVG with viewBox attribute



CAUTION: This email originated from outside of the organization. Do not click 
links or open attachments unless you recognize the sender and know the content 
is safe:
I'm trying to render a PDF page (from PDFBox) to SVG image, and in order to 
assist with browsers auto-scaling the resultant image, I find that the viewBox 
attribute should be set in the svg (root) element.  Currently using Java 8 and 
Batik 1.16.

I have looked at an old question in the list about this, but the mail archive 
seems incomplete and what I've tried from it does not work.  If I try to add 
the attribute before rendering the page via SVGGraphics2D, it simply does not 
appear in the resultant output.  If I try to add it after rendering the page, 
it actually ALSO does not appear, and my content of the element is also gone.

FWIW: I think this would be a great method to add to SVGGeneratorContext.

My code is as follows.  Can someone point out how to edit the XML/SVG such that 
the viewBox attribute is included successfully in the output?

            PDFRenderer r = new PDFRenderer(document);

            PDPage page = document.getPage(PageNumber - 1);
            PDRectangle rect = page.getMediaBox();
            int w = Math.round(rect.getWidth());
            int h = Math.round(rect.getHeight());
            String viewboxInfo = String.format("0 0 %d %d", w, h);

            String svgNS = "http://www.w3.org/2000/svg";;
            DOMImplementation impl = 
GenericDOMImplementation.getDOMImplementation();
            Document myFactory = impl.createDocument(svgNS, "svg", null);

            SVGGeneratorContext ctx = 
SVGGeneratorContext.createDefault(myFactory);
            ctx.setEmbeddedFontsOn(true);
            SVGGraphics2D g2d = new SVGGraphics2D(ctx, true);

            r.renderPageToGraphics(PageNumber - 1, g2d);

            Element root = g2d.getRoot();
            root.setAttribute("viewBox", viewboxInfo);

            try (Writer out = new OutputStreamWriter(Files.newOutputStream(new 
File(tgtFilePath).toPath()), "UTF-8"))
            {
                g2d.stream(out, true);
            }

Thanks.
-AJ
Notice: This email and any attachments are confidential and may not be used, 
published or redistributed without the prior written consent of the Institute 
of Geological and Nuclear Sciences Limited (GNS Science). If received in error 
please destroy and immediately notify GNS Science. Do not copy or disclose the 
contents.

Reply via email to