我正在Servletoutputstream上创建一个PDF. 我需要先将水印直接添加到流中,然后再将其导出为PDF. 有什么解决方案可以在不保存PDF的情况下即时添加水印或从流中获取文档对象.
I am creating a PDF on Servletoutputstream. I need to add watermark directly to the stream before exporting it to PDF. Is there any solution to add watermark on fly without having saved PDF or to get the document object from the stream.
推荐答案
@injecteer 的回答是正确的(除了他使用com.lowagie类的事实,这告诉我他正在使用 iText的过时版本,但他建议分两步创建最终的PDF.首先创建不带水印的PDF,然后创建带水印的PDF.
The answer by @injecteer is correct (apart from the fact that he uses com.lowagie classes which tells me he is using an obsolete version of iText), but he suggests creating the final PDF in two passes. First the PDF is created without a watermark, then it's created with a watermark.
正如 @mkl 在他的评论中指出的那样,如果使用页面事件,则可以一次性创建PDF.我写了一个小的水印示例.
As @mkl indicates in his comment, you can create the PDF in one go if you use page events. I've written a small Watermarking example.
这是页面事件类:
public class Watermark extends PdfPageEventHelper { protected Phrase watermark = new Phrase("WATERMARK", new Font(FontFamily.HELVETICA, 60, Font.NORMAL, BaseColor.LIGHT_GRAY)); @Override public void onEndPage(PdfWriter writer, Document document) { PdfContentByte canvas = writer.getDirectContentUnder(); ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, watermark, 298, 421, 45); } }此事件将被添加到PdfWriter中,如下所示:
This event is added to the PdfWriter like this:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest)); writer.setPageEvent(new Watermark());从现在开始,每次页面完成时,都会将Watermark事件类中定义的文本添加到现有内容下.
From now on, the text defined in the Watermark event class will be added under the existing content every time a page is completed.
更多推荐
将水印直接添加到流中
发布评论