当前位置: 首页 > 知识库问答 >
问题:

创建仅在使用PDFBox打印时显示的水印(pdf可选内容

唐阳飙
2023-03-14

我遇到过许多使用PDFBox Layer实用程序的appendFormAsLayer方法的示例,如下所示:

 /**
 * Places the given form over the existing content of the indicated page (like an overlay).
 * The form is enveloped in a marked content section to indicate that it's part of an
 * optional content group (OCG), here used as a layer. This optional group is returned and
 * can be enabled and disabled through methods on {@link PDOptionalContentProperties}.
 * @param targetPage the target page
 * @param form the form to place
 * @param transform the transformation matrix that controls the placement
 * @param layerName the name for the layer/OCG to produce
 * @return the optional content group that was generated for the form usage
 * @throws IOException if an I/O error occurs
 */
public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage,
        PDXObjectForm form, AffineTransform transform,
        String layerName) throws IOException
{
    PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        catalog.setOCProperties(ocprops);
    }
    if (ocprops.hasGroup(layerName))
    {
        throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName);
    }

    PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName);
    ocprops.addGroup(layer);

    PDResources resources = targetPage.findResources();
    PDPropertyList props = resources.getProperties();
    if (props == null)
    {
        props = new PDPropertyList();
        resources.setProperties(props);
    }

    //Find first free resource name with the pattern "MC<index>"
    int index = 0;
    PDOptionalContentGroup ocg;
    COSName resourceName;
    do
    {
        resourceName = COSName.getPDFName("MC" + index);
        ocg = props.getOptionalContentGroup(resourceName);
        index++;
    } while (ocg != null);
    //Put mapping for our new layer/OCG
    props.putMapping(resourceName, layer);

    PDPageContentStream contentStream = new PDPageContentStream(
            targetDoc, targetPage, true, !DEBUG);
    contentStream.beginMarkedContentSequence(COSName.OC, resourceName);
    contentStream.drawXObject(form, transform);
    contentStream.endMarkedContentSequence();
    contentStream.close();

    return layer;
}

前面代码中的getPDFName调用中的“mc”有什么意义?

我已经编写了下面的代码,在一个现有pdf的每一页上插入水印,并启用每一组可选内容。

    LayerUtility layerUtility = new LayerUtility(document);
    PDXObjectForm form = layerUtility.importPageAsForm(overlayDoc, 0);
    for (int i = 0; i < document.getDocumentCatalog().getAllPages().size(); i++) {
        PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(i);
        PDOptionalContentGroup ocGroup = layerUtility.appendFormAsLayer(page, form, new AffineTransform(), "watermark" + i);
    }



    PDOptionalContentProperties ocprops = document.getDocumentCatalog().getOCProperties();

    for (String groupName : ocprops.getGroupNames()) {
        if (groupName.startsWith("watermark")) {
            ocprops.setGroupEnabled(groupName, true);
        }
    }

将组设置为已启用或已禁用的“SetGroupEnabled(groupName,true)”将使其显示以供显示和打印。根据我在这个主题上研究的其他信息,当可选内容可见时,可以更精细地调优,这表示屏幕和打印布尔属性的存在,可以设置这些属性来确定内容的可见性。参见https://acrobatusers.com/tutorials/watermarking-a-pdf-with-javascript

是否有一种方法使用PDFBox使水印在打印时可见,但在显示时不可见?如果没有,请提出其他解决办法的建议。

下面是从字符串(createOverlay)和函数(addWatermark)创建水印pdf的附加代码,该函数调用传递水印文档的LayerUtility。所需要的只是从任何现有的pdf文件创建一个PDDocument,并将其与水印字符串一起传递。

public PDDocument addWatermark(PDDocument document, String text) throws IOException {
    PDDocument overlayDoc = createOverlay(text);
    //  Create the watermark in an optional content group
    LayerUtility layerUtility = new LayerUtility(document);
    PDXObjectForm form = layerUtility.importPageAsForm(overlayDoc, 0);
    for (int i = 0; i < document.getDocumentCatalog().getAllPages().size(); i++) {
        PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(i);
        layerUtility.appendFormAsLayer(page, form, new AffineTransform(), "watermark" + i);
    }
    return document;        
}

private PDDocument createOverlay(String text) throws IOException {
    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);

    PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
     // Set the transparency/opacity
     extendedGraphicsState.setNonStrokingAlphaConstant(0.4f);
     if (page.findResources() == null) {
         page.setResources(new PDResources());
     }
     PDResources resources = page.findResources();// Get the page resources.
     // Get the defined graphic states.
     if (resources.getGraphicsStates() == null)
     {
         resources.setGraphicsStates(new HashMap<String, PDExtendedGraphicsState>());
     }
     Map<String, PDExtendedGraphicsState> graphicsStateDictionary = resources.getGraphicsStates();

      if (graphicsStateDictionary != null){ 
          graphicsStateDictionary.put("TransparentState", extendedGraphicsState); 
          resources.setGraphicsStates(graphicsStateDictionary); 
     }

    // the x/y coords
    Float xVal = 0f; //Float.parseFloat(config.getProperty("ss.xVal"));
    Float yVal = 0f; //Float.parseFloat(config.getProperty("ss.yVal"));

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
      contentStream.appendRawCommands("/TransparentState gs\n");

    // Create the text and position it
    contentStream.beginText();
    contentStream.setFont(font, fontSize);
    contentStream.setTextRotation(Math.PI/4,page.getMediaBox().getWidth()/4,page.getMediaBox().getHeight()/4);
    contentStream.setNonStrokingColor(210,210,210); //light grey
    contentStream.moveTextPositionByAmount(xVal, yVal);
    contentStream.drawString(text);
    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    //return the string doc
    return document;
}

共有1个答案

勾炜
2023-03-14
private void addWaterMark(PDDocument document) throws Exception
{
    PDDocumentCatalog catalog = document.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        ocprops.setBaseState(BaseState.OFF);
        catalog.setOCProperties(ocprops);
    }
    String layerName = "conWatermark";
    PDOptionalContentGroup watermark = null;
    if (ocprops.hasGroup(layerName))
    {
        watermark = ocprops.getGroup(layerName);
    }
    else
    {
        watermark = new PDOptionalContentGroup(layerName);
        ocprops.addGroup(watermark);
    }

    COSDictionary watermarkDic = watermark.getCOSObject();
    COSDictionary printState = new COSDictionary();
    printState.setItem("PrintState", COSName.ON);
    COSDictionary print = new COSDictionary();
    print.setItem("Print", printState);
    watermarkDic.setItem("Usage", print);

    COSDictionary asPrint = new COSDictionary();
    asPrint.setItem("Event", COSName.getPDFName("Print"));
    COSArray category = new COSArray();
    category.add(COSName.getPDFName("Print"));
    asPrint.setItem("Category", category);
    COSArray ocgs = new COSArray();
    ocgs.add(watermarkDic);
    asPrint.setItem(COSName.OCGS, ocgs);
    COSArray as = new COSArray();
    as.add(asPrint);
    COSDictionary d = (COSDictionary) ((COSDictionary) ocprops.getCOSObject()).getDictionaryObject(COSName.D);
    d.setItem(COSName.AS, as);

    for (int n = 0; n < document.getNumberOfPages(); n++)
    {
        PDPage page = document.getPage(n);

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

        String text1 = "Confidential";
        String text2 = "Document ..."; //

        PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
        graphicsState.setNonStrokingAlphaConstant(0.08f);

        PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);
        contentStream.setGraphicsStateParameters(graphicsState);
        contentStream.setNonStrokingColor(Color.GRAY);

        contentStream.beginMarkedContent(COSName.OC, watermark);

        contentStream.beginText();

        PDRectangle pageSize = page.getBBox();
        float fontSize = this.getFittingFontSize(pageSize, text1);
        PDFont font = this.WATERMARK_FONT;
        contentStream.setFont(font, fontSize);
        float text1Width = this.getTextWidth(font, fontSize, text1);
        float rotation = (float) Math.atan(pageSize.getHeight() / pageSize.getWidth());
        Point p = this.getStartPoint(pageSize, fontSize, text1);
        AffineTransform at = new AffineTransform(1, 0, 0, 1, p.getX(), p.getY());
        at.rotate(rotation);
        Matrix matrix = new Matrix(at);
        contentStream.setTextMatrix(matrix);
        contentStream.showText(text1);

        fontSize = this.getFittingFontSize(pageSize, text2);
        contentStream.setFont(font, fontSize);
        contentStream.newLineAtOffset(-(this.getTextWidth(font, fontSize, text2) - text1Width) / 2, -fontSize * 1.2f);
        contentStream.showText(text2);
        contentStream.endMarkedContent();
        contentStream.endText();
        contentStream.close();
    }
}
 类似资料:
  • 问题内容: 我们正在寻找替代方法,以替代当前通过小程序在Java Web应用程序中打印支票的方式。似乎共识是使用PDF进行打印,而itext提供了使用Java进行打印的功能。 但是 ,在我们的特殊情况下,支票是“仅打印”的,这一点很重要- 用户在应用程序中不应该具有保存支票的任何能力(我知道精明的用户可以做一个PrintScreen,但我们想遮盖住后盖,在应用程序中不进行任何本机功能来保存支票)。

  • 问题内容: 我想使用PDFBox打印 由iText创建的 PDF文件 。我已经使用PDDocument类及其方法print()成功尝试了此操作。您可以在此处找到文档: http //pdfbox.apache.org/apidocs/。 (我正在使用此代码:) 方法print()很好用,但是 有一个问题:当我需要打印多个文件时,该方法要求我为每个文档选择打印机。 有什么办法只能设置一次打印机吗?

  • 问题内容: 我正在尝试使用PDFBox专门为PDF添加水印。我已经能够使图像显示在每个页面上,但是它失去了背景透明度,因为它看起来好像PDJpeg将其转换为JPG。也许有一种使用PDXObjectImage的方法。 到目前为止,这是我写的内容: 问题答案: 更新的答案 (更好的版本,带有简单的水印方法,这要感谢下面的评论员和@okok的回答提供了输入) 如果您使用的是PDFBox 1.8.10或更

  • 我有一个连接到CUPS的打印机,它支持双面打印,如何通过java例程将其设置为单面打印或双面打印? 我曾尝试使用它的库使用ASET添加和addViewer首选项没有任何运气。 有人能提供一些建议吗?

  • 我目前的工作是创建机械图纸,用于发送给客户和作为施工图。当我的绘图完成后,我导出一个. pdf文件,并将其发送给客户端。 我们的客户非常喜欢黑白画,所以我试着提供他们。但是我用来画画的软件效果不好。它只有一个选项“所有颜色都是黑色”,我的画上有一些白色的“隐藏线”。当然,这些显示使用所有颜色作为黑色选项。 我找到了一个解决方案,那就是使用pdf打印机。效果很好,效果也很好。 现在我想打印这个。pd