将PDF保存到本地磁盘C#

时间:2017-09-26 17:01:12

标签: c# winforms itext

我正在尝试将PDF保存到文档文件夹。我用谷歌搜索并遇到了很多资源,但它们都没有为我工作。我尝试过使用showfiledialog,但是没有用。我想要的是将我的PDF文件保存到文档文件夹。我需要为学校项目做这件事,这是唯一让我难过的部分。到目前为止,这是我的代码:

  private void savePDF_Click(object sender, EventArgs e)
{
    FileStream fileStream = new FileStream(nameTxtB.Text + "Repair.pdf", FileMode.Create, FileAccess.Write, FileShare.None);

    Document document = new Document(); 
    PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream);             
    pdfWriter.Open(); 
    PdfContentByte cb = pdfWriter.DirectContent;
    ColumnText ct = new ColumnText(cb);
    document.Open(); 
    ...

1 个答案:

答案 0 :(得分:1)

您应该将内容(nameTxtB.Text)添加到段落而不是FileStream

   using System.IO;
   using iTextSharp.text.pdf;
   using iTextSharp.text;

 static void Main(string[] args) {
        // open the writer
            string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Repair.pdf");
        FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
        Document doc = new Document();

        //Create a New instance of PDFWriter Class for Output File

        PdfWriter.GetInstance(doc, fs);
        //Open the Document
        doc.Open();
        //Add the content of Text File to PDF File

        doc.Add(new Paragraph("Document Content"));

        //Close the Document

        doc.Close();
        System.Diagnostics.Process.Start(fileName);
    }