如何只生成一个PDF

时间:2012-03-30 12:52:18

标签: c# pdf itextsharp

以下是我的代码我正在从ItextSharp生成密码保护的pdf。

实际上有两个pdf正在生成和保存。

但我想只保存文件。

如果我使用相同的输入和输出我会收到错误。

真的很感谢你的帮助。

Letter1 mydoc = new Letter1();
mydoc.GenerateLetter();  
string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string InputFile = Path.Combine(WorkingFolder, "Testing1.pdf");
FileStream f = new FileStream(InputFile, FileMode.Create);
f.Write(mydoc.DocumentBytes, 0, mydoc.DocumentBytes.Length);
f.Close();
string OutputFile = Path.Combine(WorkingFolder, "TestingOut1.pdf");
using (Stream input = new FileStream(InputFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
{
    using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        PdfReader reader = new PdfReader(input);
        PdfEncryptor.Encrypt(reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
    }
}  

2 个答案:

答案 0 :(得分:3)

考虑使用MemoryStream

未经测试的代码(用浏览器编写:)

using (MemoryStream m = new MemoryStream())
{
    m.Write(mydoc.DocumentBytes, 0, mydoc.DocumentBytes.Length);
    m.Seek(0, SeekOrigin.Origin);

    string OutputFile = Path.Combine(WorkingFolder, "TestingOut1.pdf");
    using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        PdfReader reader = new PdfReader(m);
        PdfEncryptor.Encrypt(reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
    }
}  

答案 1 :(得分:0)

无需实例化单独的流来读取您要加密的PDF。使用PdfReader overloaded constructor that accepts a file path。像这样:

PdfReader reader = new PdfReader(InputFile);
using (Stream output = new FileStream(
    OutputFile, FileMode.Create, FileAccess.Write, FileShare.None
))
{
  PdfEncryptor.Encrypt(
    reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS
  );    
}