将水印直接添加到流中

编程入门 行业动态 更新时间:2024-10-10 17:28:38
本文介绍了将水印直接添加到流中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在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.

更多推荐

将水印直接添加到流中

本文发布于:2023-11-09 04:07:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571360.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:水印   到流中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!