PDF盖章在没有标题信息或正文的页面上不起作用

本文关键字:正文 不起作用 信息 盖章 标题 PDF | 更新日期: 2023-09-27 17:58:56

使用以下代码pdf盖章可以正常工作,但如果pdf页面没有标题信息或正文为空,则盖章不起作用。我的意思是pdfData.ShowText(strCustomMessage)不起作用。

//create pdfreader object to read sorce pdf
PdfReader pdfReader=new PdfReader(Server.MapPath("Input") + "/" + "input.pdf");
//create stream of filestream or memorystream etc. to create output file
FileStream stream = new FileStream(Server.MapPath("Output") + "/output.pdf",  FileMode.OpenOrCreate);
//create pdfstamper object which is used to add addtional content to source pdf file
PdfStamper pdfStamper = new PdfStamper(pdfReader,stream);
//iterate through all pages in source pdf
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
//Rectangle class in iText represent geomatric representation... in this case, rectanle object would contain page geomatry
Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
//pdfcontentbyte object contains graphics and text content of page returned by pdfstamper
PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);
//create fontsize for watermark
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
//create new graphics state and assign opacity
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.4F;
//set graphics state to pdfcontentbyte
pdfData.SetGState(graphicsState);
//set color of watermark
pdfData.SetColorFill(BaseColor.BLUE);
//indicates start of writing of text
pdfData.BeginText();
//show text as per position and rotation
pdfData.SetTextMatrix(pageRectangle.Width/2,pageRectangle.Height/2);                                                                                     pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9);
string strCustomMessage="PDF Stamping Test"
pdfData.ShowText(strCustomMessage);
//call endText to invalid font set
pdfData.EndText();
}
//close stamper and output filestream
pdfStamper.Close();
stream.Close();

PDF盖章在没有标题信息或正文的页面上不起作用

我认为你的问题错了。当你说"pdf页面没有标题信息或正文为空"时,你的意思是什么?因为这没有道理。

一些观察:我认为您使用的是iTextSharp的过时版本。阅读常见问题解答,了解为什么这是个坏主意。

iTextSharp的较新版本将因为此错误引发异常:

pdfData.BeginText();
//show text as per position and rotation
string strCustomMessage="PDF Stamping Test"
pdfData.ShowText(strCustomMessage);
//call endText to invalid font set
pdfData.EndText();

在这些行中,您违反了PDF参考:您在没有定义字体和大小的情况下显示BT/ET序列中的文本。如果您使用的是iTextSharp的新版本,则会有一个例外指出这一点。您需要在BeginText()/EndText()序列内使用SetFontAndSize()方法移动行。在文本对象之外使用它是违法的。

另外:为什么使用BeginText()/EndText()添加文本?这是PDF专家的代码。阅读文档以了解如何使用ColumnText.ShowTextAligned()ShowTextAligned()方法是为不熟悉PDF语法的开发人员编写的一种方便的方法。

添加ShowText()的文本是否可见取决于:

  • 页面的不透明度:假设您的页面由扫描的图像组成,您将看不到任何文本,因为您正在图像下方添加文本。使用GetOverContent()方法而不是GetUnderContent()方法来避免这种情况
  • 页面上的位置:我看到您使用GetPageSizeWithRotation()方法获得页面的大小,但我看不到您对该信息做任何操作。我看不出你在哪个坐标显示文本。这也是错误的。您需要确保将文本添加到页面的可见区域内

此答案列出了代码中的几个问题。如果您使用ShowTextAligned()并更正X、Y坐标来简化代码,效果会更好。