草庐IT

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

coder 2024-04-05 原文

我遇到过很多使用 PDFBox Layer Utility 的 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)”会导致它在显示和打印时显示。根据我研究过的有关此主题的其他信息,可以在可选内容可见时进行更精细的调整,这表明存在 onScreen 和 onPrint boolean 属性,可以设置这些属性以确定内容的可见性。参见 https://acrobatusers.com/tutorials/watermarking-a-pdf-with-javascript

有没有办法使用 PDFBox 使水印在打印时可见但在显示时不可见?如果没有,我们将不胜感激任何替代解决方案的建议。

这里是从字符串 (createOverlay) 和调用 LayerUtility 传递水印文档的函数 (addWatermark) 创建水印 pdf 的附加代码。所需要做的就是从任何现有的 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;
}

最佳答案

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 - 创建仅在使用 PDFBox 打印时显示的水印(pdf 可选内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31683515/

有关java - 创建仅在使用 PDFBox 打印时显示的水印(pdf 可选内容)的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐