Can converted DIV to Image be downloaded as PDF

Donald Symmons 3,066 Reputation points
2023-04-10T07:06:20.85+00:00

Is it possible to convert div container to Image and at the same time download the converted image div as PDF? I tried to apply an idea from the code I have which converts HTML elements (including Image) to PDF, but it did not work. I believe there are several things I need to learn on this, which is why I came here for help and ideas on how this can be done successfully. Thank you

<style type="text/css"> 
#Image1 {
            position: absolute;
            left: 20px;
            top: 20px;
            cursor: move;
            background-color: #fafafa;
            border: solid 1px #00003D;
            font-size: 24px;
            text-align: center;
            backface-visibility: hidden;
            background: unset;
            height: 80px;
            width: 80px;
        }
 /* canvas container */
        .contentt {
            max-width: 100%;
            position: relative;
            margin: auto;
            height: auto;
            margin-top: 0%;
            /*text-align: center;*/
        }
        #dvContainer {
            position: relative;
            border-radius: 5px;
            border: none;
            width: 100%;
            height: 100%;
        }
</style>

<div class="contentt" style="width: 100%; margin: 0 auto;">
   <asp:Panel Class="print-contents" ID="Panel1" runat="server">
       <div id="dvContainer" runat="server" style="border: 0.5px solid #e4e7e8;"></div>
       <asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="80px" />
   </asp:Panel>
<asp:HiddenField ID="HiddenField1" runat="server" />
</div>

<asp:Button ID="Button1" runat="server" CssClass="btn navbar-btn" Text="Download(PDF)" UseSubmitBehavior="false" OnClick="ConvertDivToImageToPDF_Click" OnClientClick="return DownloadToPDF(this)" />

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
 <script type="text/javascript">
    function DownloadToPDF(Button1) {
      html2canvas($("#Panel1")[0]).then(function (canvas) {
        var base64 = canvas.toDataURL();
        $("[id*=HiddenField1]").val(base64);
         __doPostBack(Button1.name, "");
       });
       return false;
    }
</script>

 

//additional namespace for the PDF
using iText.Html2pdf;
using System.Security.Policy;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;

protected void ConvertDivToImageToPDF_Click(object sender, EventArgs e)
        {
            string base64 = Request.Form[HiddenField1.UniqueID].Split(',')[1];
            byte[] bytes = Convert.FromBase64String(base64);
            //saving the converted image first, as file to root folder
            File.WriteAllBytes(Server.MapPath("Doc.jpg"), bytes);
            // setting absolute url for the converted image.
            //In the below two lines, I don't know what control ID that can be used to call the converted HTML DIV to Image.
           // Image1.ImageUrl = GetUrl("Doc.jpg");
           // hfbackCard.UniqueID = GetUrl("Doc.jpg");

            var ImgUrl = Image1.ImageUrl;
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            Panel1.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
            PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
            cssResolver.AddCssFile(Server.MapPath("~/css/style2.css"), true);
            IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, PdfWriter)));
            var worker = new XMLWorker(pipeline, true);
            var xmlParse = new XMLParser(true, worker);
            pdfDoc.Open();
            xmlParse.Parse(sr);
            xmlParse.Flush();
            pdfDoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename= Doc.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            // After converting to PDF, Delete the image from the root folder.
            File.Delete(Server.MapPath("Doc.jpg"));
            Response.End();
        }

        public string GetUrl(string imagepath)
        {
            string[] splits = Request.Url.AbsoluteUri.Split('/');
            if (splits.Length >= 2)
            {
                string url = splits[0] + "//";
                for (int i = 2; i < splits.Length - 1; i++)
                {
                    url += splits[i];
                    url += "/";
                }
                return url + imagepath;
            }
            return imagepath;
        }
Developer technologies | .NET | Other
Developer technologies | ASP.NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2023-04-10T08:52:01.8+00:00

    Hi @Donald Symmons, You just need to use the following two namespaces:

    using iTextSharp.text;
    using iTextSharp.text.pdf;
    

    Use the following code:

    string base64 = Request.Form[ImageDatahf.UniqueID].Split(',')[1];
                byte[] imageBytes = Convert.FromBase64String(base64);
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);
    
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                { 
                    Document document = new Document();
                    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                    document.Open();
                    document.Add(image);
                    document.Close();
                    byte[] bytes = memoryStream.ToArray();
                    memoryStream.Close();
    
                    Response.Clear();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf");
                    Response.ContentType = "application/pdf";
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytes);
                    Response.End();
                }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.