2011-09-29 86 views
2

我在编程方面还是比较新的,但是我想创建一个程序,它可以创建一些带有一些信息的PDF文件。C#,Winform - 创建PDF

任何人都可以推荐一个简洁的方式来做到这一点,我有点需要创建一个常规的A4页面上有一张桌子..以及其他一些信息。

是否有可能在Visual Studio 2010中创建它 - 或者我需要某种类型的加载项吗?

回答

8

正如@Jon Skeet所说,你可以使用iTextSharp(它是Java iText的C#端口)。

首先,download iTextSharp(当前是5.1.2),将itextsharp.dll提取到某个位置并在Visual Studio中添加对其的引用。然后使用下面的代码,它是一个全功能的WinForms应用程序,它在A4文档中创建一个非常基本的表格。有关更多解释,请参阅代码中的注释。

using System; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

namespace Full_Profile1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

      //This is the absolute path to the PDF that we will create 
      string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.pdf"); 

      //Create a standard .Net FileStream for the file, setting various flags 
      using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) 
      { 
       //Create a new PDF document setting the size to A4 
       using (Document doc = new Document(PageSize.A4)) 
       { 
        //Bind the PDF document to the FileStream using an iTextSharp PdfWriter 
        using (PdfWriter w = PdfWriter.GetInstance(doc, fs)) 
        { 
         //Open the document for writing 
         doc.Open(); 

         //Create a table with two columns 
         PdfPTable t = new PdfPTable(2); 

         //Borders are drawn by the individual cells, not the table itself. 
         //Tell the default cell that we do not want a border drawn 
         t.DefaultCell.Border = 0; 

         //Add four cells. Cells are added starting at the top left of the table working left to right first, then down 
         t.AddCell("R1C1"); 
         t.AddCell("R1C2"); 
         t.AddCell("R2C1"); 
         t.AddCell("R2C2"); 

         //Add the table to our document 
         doc.Add(t); 

         //Close our document 
         doc.Close(); 
        } 
       } 
      } 

      this.Close(); 
     } 
    } 
} 
+3

阅读pdf ...并且不要忘记,如果您要在封闭的源应用程序中使用它,您应该支付iTextSharp。 – Bobrovsky

4

您可能想要使用库,例如​​iText,它可让您以编程方式构建PDF文档。如果你期待一个视觉设计师,我想你会感到失望;但是,我不知道任何可以让你轻松做到的事情。但是,这听起来并不像你有特别棘手的要求,所以只需编写代码来做到这一点不应该太难。

+0

我只是需要能够创建一个PDF文件,在其中的表...如果可能的话,在表中有一些不可见的边缘。 这样它看起来像我所有的文本都在一个盒子里 – Mathias

+0

@Mathias:我自己没有使用iText,但我强烈怀疑这不是太重要...... –

3

有几个库可用于此目的。这里有几个:

+0

是sharpPDf用于阅读pdf文档或获取他们的文本 – Lucifer

+0

@justandotherProgrammer不知道你在问什么...... SharpPDF是“一个实现用于创建PDF文档的不同对象的C#库”。 (这是直接从SharpPDF网站。) –

+0

好吧我认为这可能会帮助我通过代码 – Lucifer

0

我用iTextSharp的一次合并和拆分PDF,但已经失去了这些文件。但iTextSharp很好。考虑到您需要创建表格和所有表格,我认为您必须编写常规代码,然后您必须将它们转换为字节,然后创建一个PDF文件。我记得,iTextSharp是这样工作的。 希望它有帮助。