Skip to main content
 首页 » 编程设计

c#之使用 iTextSharp 填写 PDF 表格并通过电子邮件发送填写好的表格

2024年06月20日52pander-it

我有一个可以手动填写的 PDF 表单。

我想用数据动态填充它并用电子邮件发送此 PDF。

您建议使用哪个 dll 以及如何使用?

请您参考如下方法:

那么让我们开始吧, 首先使用 NuGet 将 iTextSharp 添加到您的项目中。 Link 让我们继续:

可编辑PDF中的每个字段都有自己的名字。学习这个字段名后。

private static void FillPDFForm() 
        {  
                // Original File 
                const string pdfTemplate="Uploads\CV.PDF"; 
                // New file which will be created after fillin PDF 
                var newFile ="Uploads\FilledCV.PDF" 
                var pdfReader = new PdfReader(pdfTemplate); 
                var pdfStamper = new PdfStamper(pdfReader, new FileStream( 
                    newFile, FileMode.Create)); 
                var pdfFormFields = pdfStamper.AcroFields; 
 
                // So one of our fields in PDF is FullName I am filling it with my full name 
                pdfFormFields.SetField("FullName", "Vuqar Qasimov");                     
 
                // flatten the form to remove editting options, set it to false 
                // to leave the form open to subsequent manual edits 
 
                pdfStamper.FormFlattening = false; 
                pdfStamper.FormFlattening = false; 
                pdfStamper.Close(); 
                break; 
            } 
 
        } 

Bingo 我们已经创建了文件,让我们将其附加到电子邮件中并发送

  public void SendEmailWithAttachment() 
        { 
            var objMailMessage = new MailMessage("EnterFromEmailAddress", "ReceiverEmailAddress") 
            { 
                Subject = "EnterEmailSubject", 
                IsBodyHtml = true, 
                Body = "EnterEmailBody" 
            }; 
            //You can add more attachments 
            objMailMessage.Attachments.Add(new Attachment("EnterAttachmentLocationPath"));  
            var smtp = new SmtpClient("smtp.office365.com"); 
            var login = new NetworkCredential("SenderEmail","SenderEmailPAssword"); 
            smtp.Credentials = login; 
            smtp.Port =  587; 
            smtp.EnableSsl = true;  
            smtp.Send(objMailMessage);  
        }  
  • 我使用 office 365 作为电子邮件。如果您使用不同的电子邮件帐户,您可能需要更改端口或其他凭据。
  • 根据我的经验,与其使用 iTextSharp 或其他软件包设计 PDF 文件,不如使用第三方应用程序设计 PDF 文件并用 iTextSharp 填充它。它看起来会更好,并且会花费更少的时间。