iTextSharp + FileStream = 损坏的 PDF 文件 [英] iTextSharp + FileStream = Corrupt PDF file

查看:90
本文介绍了iTextSharp + FileStream = 损坏的 PDF 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 iTextSharp 创建 pdf 文件.我的尝试将 pdf 的内容写入 MemoryStream,以便我可以将结果写入文件和数据库 BLOB.该文件已创建,大小约为 21kB,使用 Notepad++ 打开时看起来像 pdf.但是我的 PDF 查看器说它已损坏.这是一个小代码片段(仅尝试写入文件,而不是数据库):

I am trying to create a pdf file with iTextSharp. My attempt writes the content of the pdf to a MemoryStream so I can write the result both into file and a database BLOB. The file gets created, has a size of about 21kB and it looks like a pdf when opend with Notepad++. But my PDF viewer says it's currupted. Here is a little code snippet (only tries to write to a file, not to a database):

Document myDocument = new Document();
MemoryStream myMemoryStream = new MemoryStream();
PdfWriter myPDFWriter = PdfWriter.GetInstance(myDocument, myMemoryStream);
myDocument.Open();
// Content of the pdf gets inserted here
using (FileStream fs = File.Create("D:\...\aTestFile.pdf"))
{
    myMemoryStream.WriteTo(fs);
}
myMemoryStream.Close();

我犯的错误在哪里?

谢谢,诺伯特

推荐答案

我认为您的问题是您没有正确地向 PDF 添加内容.这是通过 Document.Add() 方法完成的,您可以通过调用 Document.Close() 来完成.

I think your problem was that you weren't properly adding content to your PDF. This is done through the Document.Add() method and you finish up by calling Document.Close().

然而,当您调用 Document.Close() 时,您的 MemoryStream 也会关闭,因此您将无法将其写入您的 FileStream.您可以通过将 MemoryStream 的内容存储到字节数组来解决此问题.

When you call Document.Close() however, your MemoryStream also closes so you won't be able to write it to your FileStream as you have. You can get around this by storing the content of your MemoryStream to a byte array.

以下代码片段对我有用:

The following code snippet works for me:

using (MemoryStream myMemoryStream = new MemoryStream()) {
    Document myDocument = new Document();
    PdfWriter myPDFWriter = PdfWriter.GetInstance(myDocument, myMemoryStream);

    myDocument.Open();

    // Add to content to your PDF here...
    myDocument.Add(new Paragraph("I hope this works for you."));

    // We're done adding stuff to our PDF.
    myDocument.Close();

    byte[] content = myMemoryStream.ToArray();

    // Write out PDF from memory stream.
    using (FileStream fs = File.Create("aTestFile.pdf")) {
        fs.Write(content, 0, (int)content.Length);
    }
}

这篇关于iTextSharp + FileStream = 损坏的 PDF 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆