如何在运行时覆盖两个文档

时间:2015-09-11 03:59:55

标签: java pdfbox

我需要在运行时添加水印文本,即。在创建文档时,我需要添加水印文本。我最初的方法是从文档中获取所有页面并在这些页面上添加我的文本。我确实工作,但问题是我的水印消息来自隐藏我的页面内容。请参阅我最初方法的代码。

  List pages = document.getDocumentCatalog().getAllPages();
    float fontSize = 70.0f;
    for (int i = 0; i < pages.size(); i++) {
        PDPage page = (PDPage) pages.get(i);
        PDRectangle pageSize = page.findMediaBox();
        float stringWidth = pdfFont.getStringWidth(text) * fontSize
                / 1000f;
        // calculate to center of the page
        int rotation = page.findRotation();
        boolean rotate = degree > 0;
        float pageWidth = rotate ? pageSize.getHeight() : pageSize
                .getWidth();
        float pageHeight = rotate ? pageSize.getWidth() : pageSize
                .getHeight();
        double centeredXPosition = rotate ? pageHeight / 2f
                : (pageWidth - stringWidth) / 2f;
        double centeredYPosition = rotate ? (pageWidth - stringWidth) / 2f
                : pageHeight / 2f;
        // append the content to the existing stream
        PDPageContentStream contentStream = new PDPageContentStream(
                document, page, true, true, true);
        contentStream.beginText();
        // set font and font size
        contentStream.setFont(pdfFont, fontSize);
        // set text color to red
        contentStream.setNonStrokingColor(240, 240, 240);
        if (rotate) {
            // rotate the text according to the page rotation
            contentStream.setTextRotation(degree, x, y);
        } else {
            contentStream.setTextTranslation(centeredXPosition,
                    centeredYPosition);
        }
        contentStream.drawString(text);
        contentStream.endText();
        contentStream.close();

我已经阅读了Overlay,我已经尝试过,所以我尝试改变我的方法,bcz我认为只有Overlay可以满足我的要求。我现在的方法是:

    public PDDocument createWatermarkText() {
    PDDocument watermarkDoc = new PDDocument();
    PDPage watermarkPage = new PDPage();
    try {

        watermarkDoc.addPage(watermarkPage);
        PDPageContentStream content = new PDPageContentStream(watermarkDoc,
                watermarkPage);
        content.setFont(pdfFont, fontSize);
        content.beginText();
        content.moveTextPositionByAmount(x, y);
        content.setNonStrokingColor(255, 0, 0);
        PDRectangle pageSize = watermarkPage.findMediaBox();
        float stringWidth = pdfFont.getStringWidth(text) * fontSize / 1000f;
        // int rotation = page.findRotation();
        boolean rotate = degree > 0;
        float pageWidth = rotate ? pageSize.getHeight() : pageSize
                .getWidth();
        float pageHeight = rotate ? pageSize.getWidth() : pageSize
                .getHeight();
        double centeredXPosition = rotate ? pageHeight / 2f
                : (pageWidth - stringWidth) / 2f;
        double centeredYPosition = rotate ? (pageWidth - stringWidth) / 2f
                : pageHeight / 2f;
        content.setTextRotation(degree, x, y);

        content.drawString(text);
        content.endText();
        content.close();
        // ColumnText.showTextAligned(writer.getDirectContentUnder(), align,
        // new Phrase(text, pdfFont), x, y,
        // degree);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return watermarkDoc;
}

然后调用此方法

     PDDocument wDoc = createWatermarkText();
            //document.addPage(page);
             Overlay overlay = new Overlay();

             overlay.overlay(wDoc, document);

但是这种方法没有成功,我得到了空白的pdf。任何帮助都非常感激。

1 个答案:

答案 0 :(得分:0)

这个答案试图让OP的原始方法发挥作用。

原始方法的问题,

  

我的水印消息来了,它隐藏了我的页面内容。

是由PDFBox PDPageContentStream构造函数将新流添加为 last 内容流的事实引起的,因此其操作也是最后执行的,因此涵盖之前绘制的内容。

因此,要在现有内容下推送新内容,我们必须将新流移至页面内容流中的前端位置。

为了能够这样做,我首先更改现有代码:我将水印绘图代码括在saveGraphicsStaterestoreGraphicsState中。这对于保护原始内容不受标记绘制代码的状态改变的影响是必要的,例如,文字颜色变化。

...
PDPageContentStream contentStream = new PDPageContentStream(
        document, page, true, true, true);
contentStream.saveGraphicsState();
contentStream.beginText();
// set font and font size
contentStream.setFont(pdfFont, fontSize);
// set text color to red
contentStream.setNonStrokingColor(240, 240, 240);
if (rotate) {
    // rotate the text according to the page rotation
    contentStream.setTextRotation(degree, x, y);
} else {
    contentStream.setTextTranslation(centeredXPosition,
            centeredYPosition);
}
contentStream.drawString(text);
contentStream.endText();
contentStream.restoreGraphicsState();
contentStream.close();
...

有了这个改变,我们只需要调用以下方法在原有内容下推送水印:

void pushUnder(PDDocument document)
{
    List<?> pages = document.getDocumentCatalog().getAllPages();
    float fontSize = 70.0f;
    for (int i = 0; i < pages.size(); i++) {
        PDPage page = (PDPage) pages.get(i);
        COSBase contents = page.getCOSDictionary().getDictionaryObject(COSName.CONTENTS);
        if (contents instanceof COSStreamArray)
        {
            COSStreamArray contentsArray = (COSStreamArray) contents;
            COSArray newArray = new COSArray();
            newArray.add(contentsArray.get(0));
            newArray.add(contentsArray.get(contentsArray.getStreamCount() - 1));

            for (int j = 1; j < contentsArray.getStreamCount() - 1; j++)
            {
                newArray.add(contentsArray.get(j));
            }

            COSStreamArray newStreamArray = new COSStreamArray(newArray);
            page.getCOSDictionary().setItem(COSName.CONTENTS, newStreamArray);
        }
    }
}

UnderlayText.java

(如果仔细观察这个方法,你会看到我们不会将新流移动到第一个位置而只移动到第二个位置。我们这样做是因为new PDPageContentStream(document, page, true, true, true)构造函数调用实际创建了两个新流,一个位于第一个位置,一个位于最后一个位置,第一个保存图形状态,最后一个恢复它然后包含您的操作。在前者之前移动后者将导致恢复图形状态操作开始这将是一个错误。)