如何只生成一个PDF

本文关键字:一个 PDF | 更新日期: 2023-09-27 18:29:41

下面是我的代码,我正在从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);
    }
}  

如何只生成一个PDF

考虑使用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);
    }
}  

无需实例化单独的流来读取要加密的PDF。使用接受文件路径的PdfReader重载构造函数。类似这样的东西:

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