如何使用 asp.net C# 将生成的 pdf 文件保存到项目文件夹?

How can save pdf genrated file to project folder using asp.net C#?

我已经从 html 生成了一个 pdf 文件,现在我需要将它保存到我的项目中的一个文件夹中。

我能够将生成的 pdf 文件下载到本地,但是当我将它发送到文件夹时,它已损坏并且无法打开。

    public void CreateHTML(ComplaintIntakeData cd)
{
  string formHtml = "<table class=\"MsoNormal\">";
  string complaintTypeHtml = PCSUtilities.GetComplaintTypeHTML(cd);
  string providerHtml = "";
  if (cd.Providers != null && cd.Providers.Count > 0)
  {
      providerHtml = PCSUtilities.GetProviderHTML(cd);
  }
        string facilityHtml = PCSUtilities.GetFacilityHTML(cd);
        string anonymousHtml = PCSUtilities.GetAnonymousHTML(cd);
        string contactHtml = PCSUtilities.GetContactHTML(cd);
        string patientHtml = PCSUtilities.GetPatientHTML(cd);
        string detailsHtml = PCSUtilities.GetComplaintDetailsHTML(cd);
        formHtml = formHtml + complaintTypeHtml + providerHtml + facilityHtml + anonymousHtml + contactHtml + patientHtml + detailsHtml + "</table>";
        formHtml = formHtml.Replace("''", "\"");
        // Load HTML template for letter and replace template fields with provider data
        string htmlContent = File.ReadAllText(Server.MapPath("~/ComplaintIntakeForm.html"));
        htmlContent = htmlContent.Replace("&lt;%ComplaintInformation%&gt;", formHtml);
        string fileName = "ComplaintIntakeFile_" + cd.ComplaintGuid.ToString() +".pdf";
        using (MemoryStream memStream = new MemoryStream())
        {
            try
            {
                // Load up a new PDF doc.
                iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.LETTER);

                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memStream);

                // writer.CompressionLevel = PdfStream.NO_COMPRESSION;

                // Make document tagged PDFVERSION_1_7 
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                writer.SetTagged();

                // Set document metadata
                writer.ViewerPreferences = PdfWriter.DisplayDocTitle;
                pdfDoc.AddLanguage("en-US");
                pdfDoc.AddTitle("Complaint Intake Form");
                writer.CreateXmpMetadata();

                pdfDoc.Open();

                var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                //tagProcessors.RemoveProcessor(HTML.Tag.IMG);
                //tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor());

                var cssFiles = new CssFilesImpl();
                cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                var cssResolver = new StyleAttrCSSResolver(cssFiles);
                var charset = Encoding.UTF8;
                var context = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                context.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);
                var htmlPipeline = new HtmlPipeline(context, new PdfWriterPipeline(pdfDoc, writer));
                var cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
                var worker = new XMLWorker(cssPipeline, true);
                var xmlParser = new XMLParser(true, worker, charset);

                try
                {
                    using (var sr = new StringReader(htmlContent))
                    {
                        xmlParser.Parse(sr);
                       // xmlParser.Flush();

                    }
                }
                catch (Exception e)
                {
                    Response.Write(e.Message);
                }
                
                pdfDoc.Close();

                //writer.Close();
                ///this creates a pdf download.
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                Response.OutputStream.Write(memStream.GetBuffer(), 0, memStream.GetBuffer().Length);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("The following error occurred:\n" + ex.ToString());
            }

        }
}

当我添加以下内容来创建文件时。文件已创建,但已损坏且无法以 pdf 格式打开

using (FileStream file = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew))
                {
                    byte[] bytes = new byte[memStream.Length];
                    memStream.Read(bytes, 0, memStream.Length);
                    file.Write(bytes, 0, bytes.Length);
                }

我认为这个答案是相关的:

Copy MemoryStream to FileStream and save the file?

我猜你的两个代码片段同时使用了 memStream 和 memString 并且没有在上下文中看到所有代码。假设 memStream 是一个包含 PDF 内容的 Stream,您可以将其写入这样的文件:

using (FileStream file = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew))
{
    memStream.Position = 0;
    memStream.CopyTo(file);
}

我最终将新的 FileStream 调用移动到 PdfWriter.GetInstance 方法中以代替 memStream 变量。并且能够一起摆脱使用文件流代码。

PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath(path)+"/" + fileName, FileMode.CreateNew));