C#, Winform - creating PDF
本文关键字:creating PDF Winform | 更新日期: 2023-09-27 18:09:59
我对编程还是有点陌生,但我想创建一个程序,可以创建PDF的一些信息在他们。
谁能推荐一个整洁的方式这样做,我有点需要创建一个普通的A4页上的表格…和其他一些信息。
是否有可能从Visual studio 2010中创建它-或者我需要某种像那样的加载项?
正如@Jon Skeet所说,您可以使用iTextSharp(这是Java iText的c#移植)。
首先,下载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();
}
}
}
您可能希望使用诸如iText之类的库,它将允许您以编程方式构建PDF文档。
我不清楚你所说的"在Visual Studio 2010中创建它"是什么意思——如果你期待一个视觉设计师,我想你会失望的;我不知道有什么东西能让你轻松地做到这一点。然而,听起来您并没有特别棘手的需求,所以编写代码来实现它应该不会太难。
有几个库可用于此目的。以下是一些:
- iTextSharp
- PDFSharp
- SharpPDF
我曾经使用iTextSharp一次合并和分割pdf,但已经失去了这些文件。但是iTextSharp很好。至于你需要创建表格之类的东西,我认为你必须编写常规代码,然后你必须将它们转换成字节,然后创建一个pdf文件。我记得,iTextSharp就是这样工作的。