【发布时间】:2011-11-27 21:44:07
【问题描述】:
我在编程方面还是个新手,但我想创建一个可以创建包含一些信息的 PDF 的程序。
任何人都可以推荐一种简洁的方法吗,我需要创建一个带有表格的常规 A4 页面......以及其他一些信息。
是否可以在 Visual Studio 2010 中创建它 - 还是我需要某种类似的插件?
【问题讨论】:
标签: c# winforms visual-studio pdf
我在编程方面还是个新手,但我想创建一个可以创建包含一些信息的 PDF 的程序。
任何人都可以推荐一种简洁的方法吗,我需要创建一个带有表格的常规 A4 页面......以及其他一些信息。
是否可以在 Visual Studio 2010 中创建它 - 还是我需要某种类似的插件?
【问题讨论】:
标签: c# winforms visual-studio pdf
正如@Jon Skeet 所说,您可以使用 iTextSharp(它是 Java iText 的 C# 端口)。
首先,download iTextSharp(当前为 5.1.2),将 itextsharp.dll 提取到某个位置并在 Visual Studio 中添加对它的引用。然后使用下面的代码,这是一个完整的 WinForms 应用程序,它在 A4 文档中创建一个非常基本的表格。更多解释请参见代码中的 cmets。
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();
}
}
}
【讨论】:
您可能希望使用 iText 等库,它可以让您以编程方式构建 PDF 文档。
不清楚您所说的“从 Visual Studio 2010 中创建它”是什么意思 - 如果您期待一个视觉设计师,我想您会感到失望;我不知道有什么可以让你轻松做到这一点。但是,听起来您的要求并不特别棘手,因此仅编写代码来完成它应该不会太难。
【讨论】:
有几个库可用于此目的。以下是一些:
【讨论】:
我曾经使用 iTextSharp 合并和拆分 pdf,但丢失了这些文件。但是 iTextSharp 很好。关于您需要创建表格和所有内容,我认为您必须编写常规代码,然后您必须将它们转换为字节,然后从中创建一个 pdf 文件。我记得,iTextSharp 就是这样工作的。 希望对您有所帮助。
【讨论】: