C#、Winform - 创建 PDF

标签 c# winforms visual-studio pdf

<分区>

我对编程还是有点陌生​​,但我想创建一个程序来创建包含一些信息的 PDF。

谁能推荐一种简洁的方法,我有点需要创建一个常规的 A4 页面,上面有一个表格......和一些其他信息。

是否可以从 Visual Studio 2010 中创建它 - 或者我是否需要某种类似的插件?

最佳答案

正如@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();
        }
    }
}

关于C#、Winform - 创建 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7601145/

相关文章:

c# - 如何在 ASP.Net MVC3 C#4 中延迟 Controller 操作结果

c# - 如何在 C# 中压缩具有相似文件名的多个文件

c# - 您将 Form1 重命名为什么?

visual-studio - 类名和方法名下拉列表丢失(Visual Studio 设置)

c# - 使可为空的数字向上向下c#

c# - 如何配置 Azure Function v3 使用的默认 JsonSerializerOptions (System.Text.Json)?

c# - 从没有文本框的条形码阅读器获取数据

c# - 视觉风格独立绘图

Visual Studio 中的 C++ 代码段支持?

c# - Visual Studio 认为我想连接到 SQL Server 而不是 MySQL?