iTextSharp的+ =的FileStream腐败的PDF文件 [英] iTextSharp + FileStream = Corrupt PDF file

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

问题描述

我想创建一个iTextSharp的pdf文件。我尝试写的PDF到一个MemoryStream内容,所以我可以把结果写入到两个文件和数据库BLOB。该文件被创建,有一个大小约21KB,它看起来就像当用记事本运行结束++的PDF文件。但我的PDF查看器说,它currupted。
这里是一个小code段(只尝试写入文件,而不是一个数据库):

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();

在哪里是我犯这样的错误?

Where is the mistake I make?

感谢您,
诺伯特

Thank you, Norbert

推荐答案

我觉得你的问题是,你没有正确地将内容添加到您的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.

以下code段为我的作品:

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天全站免登陆