0

I have generated a pdf file from html and now I need to save it to a folder in my project.

I am able to get the generated pdf to download locally but when I send it to the file folder it gets corrupted and will not open.

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

        }
}

when I add the following to create the file. The file is created but it is corrupted and cannot open as a 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);
                }
robbins
  • 25
  • 5

2 Answers2

0

I think this answer is relevant:

Copy MemoryStream to FileStream and save the file?

Your two code snippets use both memStream and memString and without seeing all the code in context, I'm guessing. Assuming memStream is a Stream that contains the contents of your PDF, you can write it to a file like this:

using (FileStream file = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew))
{
    memStream.Position = 0;
    memStream.CopyTo(file);
}
jbuch
  • 121
  • 3
  • The top section of code is the whole method where the memory string is used to convert the html to a pdf. The second section is what I've tried and failed. This solution is givng me "There was an error opening this document. The file is damaged and could not be repaired." similar to what this is giving – robbins Feb 04 '21 at 17:28
  • @robbins, I can't really help diagnose issues with the PDF generation itself, but if you have a valid PDF in the memory stream, the example code above will write it to disk. – jbuch Feb 04 '21 at 18:05
  • The response.OutStream.Write is creating a pdf locally. but the copyTo is not creating one within my project. – robbins Feb 04 '21 at 18:42
  • @robbins, it would help if you could post a complete example, the code above is split such that we can't see how it's connected. Can you create or share a repository link or at least a Gist with a complete example of your method? – jbuch Feb 04 '21 at 19:56
  • I have created a GIST. https://gist.github.com/jrobbinsDOH/94d573fbaf57e61a18f7e0a703db47ba – robbins Feb 08 '21 at 15:56
  • @robbins, if you put a breakpoint on what is line 76 of the gist, what is the value of memStream.Length? You are saying that NO file is created in the tempFiles directory? Are you 100% sure you are looking in the correct local path? What is the value of Server.MapPath("~/tempFiles/")? – jbuch Feb 08 '21 at 17:00
  • In the original question I stated that the file is there but is corrupted. I must have misspoke later on. the memStream length = 15. ReadTimeOut and WriteTimeOut show a System.InvalidOperation Exception. so your solution for writing the file works but doesn't address the original issue. Thank you for you help thus far. – robbins Feb 09 '21 at 17:09
0

I wound up moving the new FileStream call into the PdfWriter.GetInstance method in place of the memStream variable. And was able to get rid of the using filestream code all together.

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