gpt4 book ai didi

java - 使用 PDFBox 在 PDF 上绘制 vector 图像

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:57:44 25 4
gpt4 key购买 nike

我想用 Apache PDFBox 在 PDF 上绘制 vector 图。

这是我用来绘制常规图像的代码

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

如果我使用 svgwmf 图像而不是 png,生成的 PDF 文档就会损坏。

我希望图像成为 vector 图像的主要原因是使用 PNG 或 JPG 图像看起来很糟糕,我认为它以某种方式被压缩所以看起来很糟糕。对于 vector 图像,这不应该发生(好吧,当我在 Inkscape 中将 svg 路径导出为 PDF 时,它不会发生, vector 路径被保留)。

有没有办法使用 Apache PDFBox 将 svg 或 wmf(或其他 vector )绘制成 PDF?

如果重要的话,我目前正在使用 PDFBox 1.8。

最佳答案

看图书馆pdfbox-graphics2d , 在 this Jira 中吹捧.

您可以通过 Batik 绘制 SVG或 Salamander或其他什么,到类 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));

关于java - 使用 PDFBox 在 PDF 上绘制 vector 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com