![](/img/trans.png)
[英]Add Watermark to PDF using iTextSharp Not working for Image PDF C#
[英]c# itextsharp PDF creation with watermark on each page
我正在嘗試使用 itextsharp(Java 的 itext 的 C# 端口)以編程方式創建許多帶有水印的 PDF 文檔。
在使用 PdfStamper 創建文檔后,我可以執行此操作。 然而,這似乎涉及重新打開文檔閱讀它,然后在每頁上創建一個帶有水印的新文檔。
在文檔創建期間有沒有辦法做到這一點?
深入研究后,我發現最好的方法是在創建的每個頁面上添加水印。 為此,我創建了一個新類並實現了 IPdfPageEvent 接口,如下所示:
class PdfWriterEvents : IPdfPageEvent
{
string watermarkText = string.Empty;
public PdfWriterEvents(string watermark)
{
watermarkText = watermark;
}
public void OnOpenDocument(PdfWriter writer, Document document) { }
public void OnCloseDocument(PdfWriter writer, Document document) { }
public void OnStartPage(PdfWriter writer, Document document) {
float fontSize = 80;
float xPosition = 300;
float yPosition = 400;
float angle = 45;
try
{
PdfContentByte under = writer.DirectContentUnder;
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
under.BeginText();
under.SetColorFill(BaseColor.LIGHT_GRAY);
under.SetFontAndSize(baseFont, fontSize);
under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle);
under.EndText();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
public void OnEndPage(PdfWriter writer, Document document) { }
public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition) { }
public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { }
public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { }
public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition) { }
public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { }
public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition) { }
public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { }
}
}
這個對象被注冊來處理如下事件:
PdfWriter docWriter = PdfWriter.GetInstance(document, new FileStream(outputLocation, FileMode.Create));
PdfWriterEvents writerEvent = new PdfWriterEvents(watermark);
docWriter.PageEvent = writerEvent;
雖然 Tim 的解決方案看起來很不錯,但我已經設法使用以下代碼(也許 iTextSharp 從那時起有所改進......)來做同樣的事情(我相信):
private byte[] AddWatermark(byte[] bytes, BaseFont bf)
{
using(var ms = new MemoryStream(10 * 1024))
{
using(var reader = new PdfReader(bytes))
using(var stamper = new PdfStamper(reader, ms))
{
int times = reader.NumberOfPages;
for (int i = 1; i <= times; i++)
{
var dc = stamper.GetOverContent(i);
PdfHelper.AddWaterMark(dc, AppName, bf, 48, 35, new BaseColor(70, 70, 255), reader.GetPageSizeWithRotation(i));
}
stamper.Close();
}
return ms.ToArray();
}
}
public static void AddWaterMark(PdfContentByte dc, string text, BaseFont font, float fontSize, float angle, BaseColor color, Rectangle realPageSize, Rectangle rect = null)
{
var gstate = new PdfGState { FillOpacity = 0.1f, StrokeOpacity = 0.3f };
dc.SaveState();
dc.SetGState(gstate);
dc.SetColorFill(color);
dc.BeginText();
dc.SetFontAndSize(font, fontSize);
var ps = rect ?? realPageSize; /*dc.PdfDocument.PageSize is not always correct*/
var x = (ps.Right + ps.Left) / 2;
var y = (ps.Bottom + ps.Top) / 2;
dc.ShowTextAligned(Element.ALIGN_CENTER, text, x, y, angle);
dc.EndText();
dc.RestoreState();
}
這將在作為字節數組提供的 PDF 文檔的所有頁面上添加水印。
(您無需在創建 PDF 時執行此操作。)
它似乎適用於橫向和縱向,並且可能適用於具有混合方向的文檔。
干杯! :)
string WatermarkLocation = "D:\\Images\\superseded.png";
Document document = new Document();
PdfReader pdfReader = new PdfReader(FileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileMode.Create));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
img.SetAbsolutePosition(125, 300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)
PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
waterMark = stamp.GetOverContent(page);
waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();
// now delete the original file and rename the temp file to the original file
File.Delete(FileLocation);
File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);
我使用了第一種解決方案。 一開始我很難讓它工作。 我在我所有的公共空白下得到綠色下划線,說它會隱藏一些繼承成員。
基本上我意識到我已經添加了一個 PagePageEventHelper 並且我基本上只是刪除了 OnStartPage 的代碼。 還! 出於某種原因,我不得不使我所有的公共無效的公共覆蓋無效。
public override void OnStartPage(PdfWriter writer, Document document)
{
if (condition)
{
string watermarkText = "-whatever you want your watermark to say-";
float fontSize = 80;
float xPosition = 300;
float yPosition = 400;
float angle = 45;
try
{
PdfContentByte under = writer.DirectContentUnder;
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
under.BeginText();
under.SetColorFill(iTextSharp.text.pdf.CMYKColor.LIGHT_GRAY);
under.SetFontAndSize(baseFont, fontSize);
under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle);
under.EndText();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
}
是的,Watermark 類似乎不再存在 - 奇怪。 但是在轉換為 iTextSharp 5.3 的過程中,我發現了一個簡單的方法來為新文檔添加水印。
MemoryStream mem = new MemoryStream();
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, mem);
PdfContentByte cb = writer.DirectContent;
document.Open();
document.NewPage();
Image watermark = Image.GetInstance(WATERMARK_URI);
watermark.SetAbsolutePosition(80, 200);
document.Add(watermark);
BaseFont bf = BaseFont.CreateFont(FONT, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
...
cb.EndText();
document.Close();
你不能在你做完之后在每一頁上放水印嗎?
在 iTextSharp 中,您應該能夠以編程方式添加水印,例如
Watermark watermark = new Watermark(Image.getInstance("watermark.jpg"), 200, 420);
document.Add(watermark);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.