Skip to main content
 首页 » 编程设计

c#之使用带有窗口窗体的 iTextSharp 创建 pdf

2024年02月23日16zhujiabin

我正在尝试在我的 windows 窗体应用程序 中创建一个 pdf 文档,在该应用程序中我有表单和用户控件,其中包含多个控件,例如 文本框, richtexbox, label, button, radiobutton 等...

我想用这些表单和用户控件中的数据创建 pdf,pdf 应该看起来像那些表单和用户控件中的内容,按钮、文本框、标签等,类似于这些表单中的图片和用户控件。

抱歉,如果我不清楚,我想添加用户在表单中看到的内容,就像图片一样,而不是做屏幕截图,就像做这样的事情:

pdfDocument.Add(Button); 
pdfDocument.Add(textBox); 

也许这个问题不对,但我是生成PDF的新手。

请您参考如下方法:

要使用屏幕截图方法,您可以这样做:

using (Bitmap b = new Bitmap(this.Width, this.Height)) 
{ 
    using (Graphics g = Graphics.FromImage(b)) 
    { 
        g.CopyFromScreen(this.Location, new Point(0, 0), this.Size); 
    } 
    Document doc = new Document(); 
    iTextSharp.text.Image i = iTextSharp.text.Image.GetInstance(b, System.Drawing.Imaging.ImageFormat.Bmp); 
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@"C:\Temp\output.pdf", FileMode.Create)); 
    doc.SetPageSize(new iTextSharp.text.Rectangle(this.Size.Width + doc.LeftMargin + doc.RightMargin, this.Size.Height + doc.TopMargin + doc.BottomMargin)); 
 
    doc.Open(); 
 
    doc.Add(i); 
    doc.Close(); 
}