2012-01-06 45 views
-1

我正在處理將在Intranet Web服務器上呈現PDF文檔的類。我遇到的問題是iTextSharp使用PDFWriter呈現條形碼圖像,我正在嘗試在呈現文檔之前構建IElements的集合。有沒有辦法創建一個包含條形碼圖像的集合,還是有更好的方法來編寫這個類?iTextSharp將條形碼存儲爲元素 - 空引用異常

希望我的代碼能更好地解釋它。謝謝。

public class PDFDoc 
{ 

    public float Width { get; set; } 
    public float Height { get; set; } 
    private List<IElement> Elements { get; set;} 
    ... 
    private MemoryStream ms = new MemoryStream(); 
    private Document doc = new Document(); 
    private PdfWriter writer; 

    private void initializeDocument() 
    { 
     doc = new Document(new Rectangle(Width, Height), marginLeft, marginRight, marginTop, marginBottom); 
     writer = PdfWriter.GetInstance(doc, ms); 
     Elements = new List<IElement>(); 
    } 

    private FileStreamResult GenerateLabel(IEnumerable<IElement> elements) 
    { 
     doc.Open(); 
     foreach (var e in elements) 
     { 
      doc.Add(e); 
     } 
     //doc.Add(GenerateBarcodeImage("123456")); //GenBC works here but not below 
     writer.CloseStream = false; 
     doc.Close(); 

     byte[] byteinfo = ms.ToArray(); 
     ms.Write(byteinfo, 0, byteinfo.Length); 
     ms.Position = 0; 
     ms.Seek(0, SeekOrigin.Begin); 
     return new FileStreamResult(ms, "application/pdf"); 
    } 

    private Image GenerateBarcodeImage(string code) 
    { 
     Barcode128 code128 = new Barcode128(); 
     code128.Code = code; 
     code128.X = 1f; 
     return code128.CreateImageWithBarcode(new PdfContentByte(writer), null, null); 
    } 

//Program 
     public FileStreamResult RenderLabel() 
    { 
     Elements.Add(new Paragraph("This is a test")); 
     Elements.Add(GenerateBarcodeImage("123456")); //This gives a null ref exception. 
     return GenerateLabel(Elements); 
    } 

回答

0

與代碼段的問題是,你想打電話Document.Close()後訪問MemoryStream。您可以將Close()呼叫移動到您撥打ms.ToArray()的下方,或者完全取消MemoryStream

當你實例化一個PdfWriter,你可以使用任何可用Stream,那麼爲什麼不使用Response.OutputStream

List<IElement> Elements = new List<IElement>();  
using (Document document = new Document()) { 
    PdfWriter writer = PdfWriter.GetInstance(
    document, Response.OutputStream 
); 
    document.Open(); 
    PdfContentByte cb = writer.DirectContent; 
    for (int i = 0; i < 9; ++i) { 
    Barcode128 code128 = new Barcode128(); 
    code128.Code = "code " + i.ToString(); 
    Elements.Add(code128.CreateImageWithBarcode(cb, null, null)); 
    } 
    for (int i = 0; i < Elements.Count; ++i) { 
    document.Add(new Paragraph("Barcode: " + i.ToString())); 
    document.Add(Elements[i]); 
    } 
} 
+0

感謝您的反饋意見。在讀完代碼後,我意識到我的問題不是Closed()被調用,而是Open()沒有被調用。我移動了doc.Open();到initializeDocument()方法,它工作正常。我正在使用一個內存流來處理MVC中的FileStreamResult。 – Pete 2012-01-06 16:32:51