iTextSharp 文档在部署后不工作

iTextSharp Document Isn't Working After Deployment

我正在使用 iTextSharp 创建 pdf 文档,然后将其添加为附件以使用 SendGrid 发送电子邮件。 代码在本地运行,但在 Azure 中部署项目后,此功能因某种原因停止运行。我试图分析问题,我认为由于连接,文档没有完全创建或附加。我无法确定要解决的确切问题。欢迎任何意见或讨论。

操作:

        public async Task<IActionResult> GeneratePDF(int? id, string recipientEmail)
        {
            //if id valid
            if (id == null)
            {
                return NotFound();
            }
            var story = await _db.Stories.Include(s => s.Child).Include(s => s.Sentences).ThenInclude(s => s.Image).FirstOrDefaultAsync(s => s.Id == id);

            if (story == null)
            {
                return NotFound();
            }
            var webRootPath = _hostingEnvironment.WebRootPath;
            var path = Path.Combine(webRootPath, "dump"); //folder name
            try
            {
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                {
                    iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 10, 10);
                    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                    document.Open();

                    string usedFont = Path.Combine(webRootPath + "\fonts\", "arial.TTF");
                    BaseFont bf = BaseFont.CreateFont(usedFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    iTextSharp.text.Font titleFont = new iTextSharp.text.Font(bf, 40);
                    iTextSharp.text.Font sentencesFont = new iTextSharp.text.Font(bf, 15);
                    iTextSharp.text.Font childNamewFont = new iTextSharp.text.Font(bf, 35);

                    PdfPTable T = new PdfPTable(1);
                    //Hide the table border
                    T.DefaultCell.BorderWidth = 0;
                    T.DefaultCell.HorizontalAlignment = 1;
                    T.DefaultCell.PaddingTop = 15;
                    T.DefaultCell.PaddingBottom = 15;
                    //Set RTL mode
                    T.RunDirection = PdfWriter.RUN_DIRECTION_RTL;

                    //Add our text
                    if (story.Title != null)
                    {
                        T.AddCell(new iTextSharp.text.Paragraph(story.Title, titleFont));
                    }
                    if (story.Child != null)
                    {
                        if (story.Child.FirstName != null && story.Child.LastName != null)
                        {
                            T.AddCell(new iTextSharp.text.Phrase(story.Child.FirstName + story.Child.LastName, childNamewFont));
                        }
                    }
                    if (story.Sentences != null)
                    {
                        .................
                    }
                    document.Add(T);
                    writer.CloseStream = false;
                    document.Close();

                    byte[] bytes = memoryStream.ToArray();
                    var fileName = path + "\PDF" + DateTime.Now.ToString("yyyyMMdd-HHMMss") + ".pdf";

                    using (FileStream fs = new FileStream(fileName, FileMode.Create))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }
                    memoryStream.Position = 0;
                    memoryStream.Close();
                    //Send generated pdf as attchment
                    // Create  the file attachment for this email message.
                    var attachment = Convert.ToBase64String(bytes);
                    var client = new SendGridClient(Options.SendGridKey);
                    var msg = new SendGridMessage();
                    msg.From = new EmailAddress(SD.DefaultEmail, SD.DefaultEmail);
                    msg.Subject = story.Title;
                    msg.PlainTextContent = "................";
                    msg.HtmlContent = "..................";
                    msg.AddTo(new EmailAddress(recipientEmail));
                    msg.AddAttachment("Story.pdf", attachment);
                    try
                    {
                        await client.SendEmailAsync(msg);
                    }
                    catch (Exception ex)
                    {

                        Console.WriteLine("{0} First exception caught.", ex);
                    }
                    //Remove form root
                    if (System.IO.File.Exists(fileName))
                    {
                        System.IO.File.Delete(fileName);
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"The file was not found: '{e}'");
            }
            catch (DirectoryNotFoundException e)
            {
                Console.WriteLine($"The directory was not found: '{e}'");
            }
            catch (IOException e)
            {
                Console.WriteLine($"The file could not be opened: '{e}'");
            }

            return RedirectToAction("Details", new { id = id });
        }


尝试如下编辑 usedfont 变量:

var usedfont  = Path.Combine(webRootPath ,@"\fonts\arial.TTF")

原来问题出在iTextSharp上很远。我从 this 文章中进行了远程调试。 代码的两个部分导致了问题。 首先,由于某种原因,文件夹“dump”不是在 Azure wwwroot 文件夹上创建的,而在本地。所以,我添加了这些行:

var webRootPath = _hostingEnvironment.WebRootPath;
        var path = Path.Combine(webRootPath, "dump");
        if (!Directory.Exists(path)) //Here
            Directory.CreateDirectory(path);

其次,调试后发现每次创建文件都失败。我替换了以下行:

using (FileStream fs = new FileStream(fileName, FileMode.Create))
                {
                    fs.Write(bytes, 0, bytes.Length);
                }
                memoryStream.Position = 0;
                memoryStream.Close();

与:

using (FileStream fs = new FileStream(fileName, FileMode.Create))
                using (var binaryWriter = new BinaryWriter(fs))
                {
                    binaryWriter.Write(bytes, 0, bytes.Length);
                    binaryWriter.Close();
                }
                memoryStream.Close();

希望这 post 对某人有所帮助。