PDFbox - 如何将内容添加到图层? [英] PDFbox - how can i add content to a layer?

查看:159
本文介绍了PDFbox - 如何将内容添加到图层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 pdfbox 2.0.8 - 需要创建一个图层并在那里添加一些图形.

I'm using pdfbox 2.0.8 - need to create a layer and add some graphic there.

我从我如何制作对 pdf 中现有图层(可选内容组)的修改?

然而,它基于 1.8.我尝试适应 2.0 并设法创建图层,但完全不清楚如何创建新资源并将其添加到图层 - 即 props.putMapping(resourceName, layer);必须重写 1.8 中的内容

which however is based on 1.8. I tried to adapt to 2.0 and managed to create the layer, but it is completely unclear how then you can create a new resource and add it to the layer - i.e. how the props.putMapping(resourceName, layer); which was in 1.8 has to be rewritten

推荐答案

等效于 OP 引用的答案中的 PDFBox 1.8 代码 是以下代码:

Equivalent to the PDFBox 1.8 code in the answer referenced by the OP is the following code:

void addTextToLayer(PDDocument document, int pageNumber, String layerName, float x, float y, String text) throws IOException
{
    PDDocumentCatalog catalog = document.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        catalog.setOCProperties(ocprops);
    }
    PDOptionalContentGroup layer = null;
    if (ocprops.hasGroup(layerName))
    {
        layer = ocprops.getGroup(layerName);
    }
    else
    {
        layer = new PDOptionalContentGroup(layerName);
        ocprops.addGroup(layer);
    }

    PDPage page = (PDPage) document.getPage(pageNumber);

    PDResources resources = page.getResources();
    if (resources == null)
    {
        resources = new PDResources();
        page.setResources(resources);
    }

    PDFont font = PDType1Font.HELVETICA;

    PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);
    contentStream.beginMarkedContent(COSName.OC, layer);
    contentStream.beginText();
    contentStream.setFont(font, 12);
    contentStream.newLineAtOffset(x, y);
    contentStream.showText(text);
    contentStream.endText();
    contentStream.endMarkedContent();

    contentStream.close();
}

(AddContentToOCG)

可以这样使用:

PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);

addTextToLayer(document, 0, "MyLayer", 30, 600, "Text in new layer 'MyLayer'");
addTextToLayer(document, 0, "MyOtherLayer", 230, 550, "Text in new layer 'MyOtherLayer'");
addTextToLayer(document, 0, "MyLayer", 30, 500, "Text in existing layer 'MyLayer'");
addTextToLayer(document, 0, "MyOtherLayer", 230, 450, "Text in existing layer 'MyOtherLayer'");

document.save(new File(RESULT_FOLDER, "TextInOCGs.pdf"));
document.close();

(AddContentToOCG 测试 testAddContentToNewOrExistingOCG)

这篇关于PDFbox - 如何将内容添加到图层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆