Bac*_*ash 9 java pdf image vector pdfbox
我想用Apache PDFBox在PDF上绘制矢量图像.
这是我用来绘制常规图像的代码
PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(1);
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
BufferedImage _prevImage = ImageIO.read(new FileInputStream("path/to/image.png"));
PDPixelMap prevImage = new PDPixelMap(document, _prevImage);
contentStream.drawXObject(prevImage, prevX, prevY, imageWidth, imageHeight);
如果我使用svg或wmf图像而不是png,则生成的PDF文档会损坏.
我希望图像成为矢量图像的主要原因是使用PNG或JPG图像看起来很糟糕,我认为它会以某种方式压缩,因此看起来很糟糕.使用矢量图像时,这不应该发生(好吧,当我在Inkscape中将svg路径导出为PDF时,它不会发生,矢量路径会被保留).
有没有办法使用Apache PDFBox将svg或wmf(或其他向量)绘制成PDF?
我现在正在使用PDFBox 1.8,如果这很重要.
小智 5
请参阅此 Jira中推荐的库pdfbox-graphics2d。
您可以通过Batik或Salamander或其他方式将 SVG 绘制到类上PdfBoxGraphics2D,这与 iText 的template.createGraphics(). 请参阅 GitHub 页面获取示例。
PDDocument document = ...;
PDPage page = ...; // page whereon to draw
String svgXML = "<svg>...</svg>";
double leftX = ...;
double bottomY = ...; // PDFBox coordinates are oriented bottom-up!
// I set these to the SVG size, which I calculated via Salamander.
// Maybe it doesn't matter, as long as the SVG fits on the graphic.
float graphicsWidth = ...;
float graphicsHeight = ...;
// Draw the SVG onto temporary graphics.
var graphics = new PdfBoxGraphics2D(document, graphicsWidth, graphicsHeight);
try {
    int x = 0;
    int y = 0;
    drawSVG(svg, graphics, x, y); // with Batik, Salamander, or whatever you like
} finally {
    graphics.dispose();
}
// Graphics are not visible till a PDFormXObject is added.
var xform = graphics.getXFormObject();
try (var contentWriter = new PDPageContentStream(document, page, AppendMode.APPEND, false)) { // false = don't compress
    // XForm objects have to be placed via transform,
    // since they cannot be placed via coordinates like images.
    var transform = AffineTransform.getTranslateInstance(leftX, bottomY);
    xform.setMatrix(transform);
    // Now the graphics become visible.
    contentWriter.drawForm(xform);
}
并且...如果您还想将 SVG 图形缩放至 25% 大小:
// Way 1: Scale the SVG beforehand
svgXML = String.format("<svg transform=\"scale(%f)\">%s</svg>", .25, svgXML);
// Way 2: Scale in the transform (before calling xform.setMatrix())
transform.concatenate(AffineTransform.getScaleInstance(.25, .25));
小智 0
我这样做,但不是直接这样做。首先使用 FOP 库和 Batik 将 SVG 文档转换为 PDF 文档。 https://xmlgraphics.apache.org/fop/dev/design/svg.html。
第二次,您可以使用 pdfbox 中的 LayerUtility 将新的 pdf 文档转换为 PDXObjectForm。之后,只需在最终的 pdf 文档中包含 PDXObjectForm 即可。
| 归档时间: | 
 | 
| 查看次数: | 4087 次 | 
| 最近记录: |