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

2 Answers 2

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);
}
7
  • 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 4, 2021 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 4, 2021 at 18:05
  • The response.OutStream.Write is creating a pdf locally. but the copyTo is not creating one within my project.
    – robbins
    Feb 4, 2021 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 4, 2021 at 19:56
  • I have created a GIST. gist.github.com/jrobbinsDOH/94d573fbaf57e61a18f7e0a703db47ba
    – robbins
    Feb 8, 2021 at 15:56
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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.