Rectangle rec = new Rectangle(766, 1500);
Document document = new Document(rec);
document.SetMargins(22, 22, 22, 22);
string pdfPath = Server.MapPath("~/Export/" + strAccount + "/Exports/" + strAgentID) + "/" + strReportName + ".pdf";
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.OpenOrCreate));
document.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
var cssResolver //= new StyleAttrCSSResolver(cssFiles);
= XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
var pipeline =
new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext,
new PdfWriterPipeline(document, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
TextReader tr = new StringReader(htmlFileData);
p.Parse(tr);
document.Close();
//********************* Add text watermark for pdf created above ************************************************************
string strPDFPath = Server.MapPath("~/Export" + "/" + strAccount + "/Exports/" + strAgentID + "/" + strReportName + ".pdf");
PdfReader pdfReader = new PdfReader(strPDFPath);
FileStream stream = new FileStream(strPDFPath, FileMode.OpenOrCreate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.4F;
pdfData.SetGState(graphicsState);
pdfData.SetColorFill(BaseColor.BLUE);
pdfData.BeginText();
pdfData.ShowTextAligned(Element.ALIGN_CENTER, "FOR BETA TEST ONLY", pageRectangle.Width / 2, pageRectangle.Height / 2, 45);
pdfData.EndText();
}
pdfStamper.Close();
stream.Close();
//******************************************************************************
在上面的代码中,pdf
已成功创建,但在我们尝试添加水印的块中发生异常。
在水印分配块中,strPDFPath以形式给出准确的路径
D:\\MyTestProject\\Reports\\Export\\SIP\\Exports\\BEEC1308\\1004MC_RevA.pdf
这是文件的确切位置。如果我打开这个
浏览器中的路径然后我得到正确的PDF。但是当我正在使用时读取文件路径
PdfReader pdfReader = new PdfReader(strPDFPath);
提出上述exception
。上面的代码出错或是否需要在单个块中组合水印和PDF
创建。
答案 0 :(得分:2)
您正在同时阅读和写入相同的PDF。我假设不是这样的:
//Incorrect
PdfReader pdfReader = new PdfReader(strPDFPath);
你想这样做:
//Correct
PdfReader pdfReader = new PdfReader(pdfPath);