2012-11-13 103 views
1

我正在使用以下代碼在頁面上添加水印,但輸出MemoryStream始終爲空,我在想我在哪裏做錯了。使用itextsharp在整個pdf頁面上添加水印時出錯

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; 
    } 
} 

當輸出流被進一步查看時,顯示以下錯誤。

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' 
+0

嘗試在看看功能代碼:http://stackoverflow.com/questions/2372041/c-sharp-itextsharp-pdf-creation-with-watermark-on-each-page –

+0

返回字節[ ]而不是處置流(因爲使用聲明)。 return output.ToArray(); – VahidN

回答

1

問題通過在上面的代碼中返回字節而不是存儲流來解決。

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

我有同樣的問題,但我通過這個答案擺脫了這一點。謙虛了埃米爾 – Freak

相關問題