简体   繁体   English

使用itextsharp在整个pdf页面上添加水印时出错

[英]Error when adding watermark on whole pdf page using itextsharp

I am using following code for adding watermark on a page but output MemoryStream is always empty, I am wondering where I have done wrong. 我正在使用以下代码在页面上添加水印,但输出MemoryStream始终为空,我想知道我做错了什么。

public static MemoryStream testwatermark(MemoryStream pdf)
{
    PdfReader reader = new PdfReader(pdf);

    using (MemoryStream output = new MemoryStream())
    {
        PdfStamper pdfStamper = new PdfStamper(reader, output);

        for (int pageIndex = 1; pageIndex <= reader.NumberOfPages; pageIndex++)
        {
            iTextSharp.text.Rectangle pageRectangle = reader.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);     
            //set color of watermark     
            pdfData.SetColorFill(BaseColor.BLUE);
            pdfData.BeginText();     
            //show text as per position and rotation     
            pdfData.ShowTextAligned(Element.ALIGN_CENTER, "BlueLemonCode", pageRectangle.Width / 2, pageRectangle.Height / 2, 45);     
            //call endText to invalid font set     
            pdfData.EndText();
        }
        pdfStamper.Close();
        return output;
    }
}

Following error is shown when output stream is further viewed. 进一步查看输出流时,显示以下错误。

CanRead = false
CanSeek = false
CanWrite = false
Capacity = 'output.Capacity' threw an exception of type 'System.ObjectDisposedException'
Length = 'output.Length' threw an exception of type 'System.ObjectDisposedException'
Position = 'output.Position' threw an exception of type 'System.ObjectDisposedException'

Problem is solved by returning bytes instead of memorystream in the above code. 通过返回上述代码中的字节而不是内存流来解决问题。

.
.
.
.
pdfStamper.Close();
return output;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM