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