如何从iText pdf转换器返回二进制流

时间:2015-03-09 16:13:23

标签: c# pdf itext

是否可以从pdfstamper返回二进制流(byte [])?

基本上,目标是编辑PDF文档并替换特定文本。

已经以二进制流(byte [])

输入

我在C#环境& amp;用于PDF编辑库的iText。

这是我的代码:

PdfReader reader = new PdfReader(Mydoc.FileStream);
PdfDictionary dict = reader.GetPageN(1);
PdfObject pdfObject = dict.GetDirectObject(PdfName.CONTENTS);
if (pdfObject.IsStream())
{
PRStream stream = (PRStream)pdfObject;
byte[] data = PdfReader.GetStreamBytes(stream);
stream.SetData(System.Text.Encoding.ASCII.GetBytes(System.Text.Encoding.ASCII.    GetString(data).Replace("[TextReplacement]", "Hello world")));
}
FileStream outStream = new FileStream(dest, FileMode.Create);
PdfStamper stamper = new PdfStamper(reader, outStream);
reader.Close();

return newPDFinStream // this result should be in stream byte[]

了解 FileStream 需要输出文件路径,如C:\ location \ new.pdf

有可能不临时保存吗?并直接返回二进制文件?

1 个答案:

答案 0 :(得分:2)

当然,只需将其保存到MemoryStream

using (MemoryStream ms = new MemoryStream())
{
    // Odd to have a constructor but not use the newly-created object.
    // Smacks of the constructor doing too much.
    var ignored = new PdfStamper(reader, ms);
    return ms.ToArray();
}