How can word file displayed in a div container be printed in a pdf format?

Donald Symmons 2,881 Reputation points
2023-03-28T10:44:36.1866667+00:00

I am trying to have a single page that will can be used to display either a word (.doc/.docx) or a PDF file. Instead of having two pages, each for word and pdf files. It’s a success but printing either of these formats in PDF is where I have issues.

After inserting a word or pdf file into my database table and redirect to another page, the word/pdf file is displayed on the redirected page. On the page, there is a div container that the word or pdf file will be displayed in. I want to learn how to print the file in PDF that displays there regardless of the format (whether it’s a .doc, .docx or .pdf file that displays in there).

Here is the HTML with the div container that displays word or pdf files


<div class="col-sm-10" style="width: 100%; padding: 10px; margin: 0 auto;">
                        <div class="col-sm-10" style="margin: 0 auto; padding: 6px;">
                            <div class="container-fluid" id="card" style="width: 100%; height: 100%; margin: 0 auto; border: 1px solid #e4e7e8;">
                                <div id="parent" style="margin: 0 auto; display: flex; position: center; width: 100%;">
                                    <div class="contentt" runat="server" id="DivContent" style="margin: 0 auto;">
                                        <div id="dvContainer" runat="server" style="margin: 0 auto;"></div>
                                         <asp:Image ID="Image1" runat="server" ImageUrl="TesingImg.jpg" BorderStyle="None" Width="80px" Height="80px" />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <asp:Button ID="Downloadbtn" Text="Download" runat="server"/>
                    </div>

This is how the file is being selected from the database using Web method static object, GetFile().

        [WebMethod(EnableSession = true)]
        public static object GetFile()
        {
            try
            {
                string fileName = String.Empty;
                byte[] bytes = null;
                string type = string.Empty;
                string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM DocumentTable WHERE Id = @Id", con))
                    {
                        cmd.Parameters.AddWithValue("@Id", HttpContext.Current.Session["DocumentID"]);
                        con.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            if (dr.Read())
                            {
                                fileName = dr["Name"].ToString();
                                bytes = (byte[])dr["Data"];
                                type = dr["ContentType"].ToString();
                            }
                        }
                        con.Close();
                    }
                }
                return new { Name = fileName, Data = bytes, ContentType = type };
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }

Plugins

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
    <script type="text/javascript" src="https://volodymyrbaydalka.github.io/docxjs/dist/docx-preview.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.18/mammoth.browser.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf_viewer.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
    <script src="~/js/bootstrap.min.js"></script>
    <script src="~/docx-preview.min.js"></script>
    <script src="~/js/docx-preview.js"></script>
    <script type="text/javascript" src="~/Scripts/docx-preview.js"></script>

Javascript function that displays the file (.doc, .docx or .pdf) on the page.

<script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                url: "2.aspx/GetFile",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    if (r.d.ContentType != 'application/pdf') {
                        var doc = new File([new Uint8Array(r.d.Data)], r.d.ContentType);
                        if (doc != null) {
                            var docxOptions = Object.assign(docx.defaultOptions, {
                                useMathMLPolyfill: true
                            });
                            var container = document.querySelector("#dvContainer");
                            container.innerHTML = "";
                            docx.renderAsync(doc, container, null, docxOptions);
                        }
                    }
                    else {
                        LoadPdfFromBlob(r.d.Data);
                    }
                }
            });
        });

        var pdfjsLib = window['pdfjs-dist/build/pdf'];
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';
        var pdfDoc = null;
        var scale = 1;
        var resolution = 1;

        function LoadPdfFromBlob(blob) {
            pdfjsLib.getDocument({ data: blob }).promise.then(function (pdfDoc_) {
                pdfDoc = pdfDoc_;
                var pdf_container = document.getElementById("dvContainer");
                pdf_container.innerHTML = "";
                pdf_container.style.display = "block";
                for (var i = 1; i <= pdfDoc.numPages; i++) {
                    RenderPage(pdf_container, i);
                }
            });
        };
        function RenderPage(pdf_container, num) {
            pdfDoc.getPage(num).then(function (page) {
                var canvas = document.createElement('canvas');
                canvas.id = 'pdf-' + num;
                ctx = canvas.getContext('2d');
                pdf_container.appendChild(canvas);

                var spacer = document.createElement("div");
                spacer.style.height = "20px";
                pdf_container.appendChild(spacer);

                var viewport = page.getViewport({ scale: scale });
                canvas.height = resolution * viewport.height;
                canvas.width = resolution * viewport.width;

                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport,
                    transform: [resolution, 0, 0, resolution, 0, 0]
                };

                page.render(renderContext);
            });
        };
    </script>

I tried to enclose the div container in a printpanel and use this pdf print method to print but it did not work. Please how can I do this?

<asp:Panel ID="Panel1" runat="server">
                                        <div class="contentt" runat="server" id="DivContent" style="margin: 0 auto;">
                                            <div id="dvContainer" runat="server" style="margin: 0 auto;"></div>
                                            <asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="80px" />
                                        </div>
                                    </asp:Panel>

<asp:Button ID="Downloadbtn" Text="Download" runat="server" OnClick="Downloadbtn_Click"/>

There is an image control also in the div tag. the image control can be moved to change position dynamically to anywhere in the div an be printed along with the word/pdf file.

Here is the javascript that aids in moving the image control to a desired location in the div tag

<script type="text/javascript">
        var dragItem = document.querySelector("#Image1");
        var container = document.querySelector("#subpage");

        var active = false;
        var currentX;
        var currentY;
        var initialX;
        var initialY;
        var xOffset = 0;
        var yOffset = 0;

        document.addEventListener("touchstart", dragStart, false);
        document.addEventListener("touchend", dragEnd, false);
        document.addEventListener("touchmove", drag, false);

        document.addEventListener("mousedown", dragStart, false);
        document.addEventListener("mouseup", dragEnd, false);
        document.addEventListener("mousemove", drag, false);

        function dragStart(e) {
            if (e.type === "touchstart") {
                initialX = e.touches[0].clientX - xOffset;
                initialY = e.touches[0].clientY - yOffset;
            } else {
                initialX = e.clientX - xOffset;
                initialY = e.clientY - yOffset;
            }

            if (e.target === dragItem) {
                active = true;
            }
        }

        function dragEnd(e) {
            initialX = currentX;
            initialY = currentY;
            active = false;
        }

        function drag(e) {
            if (active) {

                e.preventDefault();

                if (e.type === "touchmove") {
                    currentX = e.touches[0].clientX - initialX;
                    currentY = e.touches[0].clientY - initialY;
                } else {
                    currentX = e.clientX - initialX;
                    currentY = e.clientY - initialY;
                }

                xOffset = currentX;
                yOffset = currentY;

                setTranslate(currentX, currentY, dragItem);
            }
        }

        function setTranslate(xPos, yPos, el) {
            el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
        }
    </script>

PDF Printing

protected void Downloadbtn_Click(object sender, EventArgs e)
        {
            Response.ContentType = "Application/pdf";
            Response.AddHeader("Content-Disposition", "Attachment; filename=Document.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter StringWriter = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(StringWriter);
            DivContent.RenderControl(hw);
            Document doc = new Document(PageSize.A4,50f,50f,100f,30f);
            HTMLWorker htw = new HTMLWorker(doc);
            PdfWriter.GetInstance(doc, Response.OutputStream);
            doc.Open();
            StringReader sr = new StringReader(StringWriter.ToString());
            htw.Parse(sr);
            doc.Close();Response.Write(doc);
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,861 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,490 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,936 questions
{count} votes

Accepted answer
  1. QiYou-MSFT 4,321 Reputation points Microsoft Vendor
    2023-03-30T09:21:08.68+00:00

    Hi @Donald Symmons

    WordToPDF(string sourcePath, string targetPath);

    'sourcePath': The address of the Word file. Depending on your needs, this address is obtained from the database.

    ‘targetPath’: This is the address where your converted PDF file is stored.

    Let me share my thoughts:

    1.First of all, the PDF file can be downloaded directly, which is actually similar to printing.

    2.Of course, we need to review this file before downloading (printing). In general, word files cannot be displayed on HTML. We often convert word files into HTML files or PDF files. Here I convert it into a pdf file for presentation.

    3.I think in webform, using the backend is more convenient than using js. So I'm not using js here.

    Procedure:

    1.First, we enter characters into 'TextBox' to make us make a database query to get the file address.

    2.We find this file and convert it to pdf.

    3.'<a>' tab display and download function.

    Code:

    public string str;
            protected void Page_Load(object sender, EventArgs e)
            {
                str = "Scripts/" + TextBox1.Text + ".pdf";
                Page.DataBind();
            }
            protected void Button1_Click(object sender, EventArgs e)
            {
                string connString1 = "Data Source=localhost;Initial Catalog=TestSQL;Integrated Security=TRUE";
                using (SqlConnection conn = new SqlConnection(connString1))
                {
                    conn.Open();
                    SqlCommand sqlcom = new SqlCommand("select FilePath from dbo.File1 where FileName = '" + TextBox1.Text + "'", conn);
                    string path= Convert.ToString(sqlcom.ExecuteScalar());
                    TextBox2.Text = path;
                    WordToPDF("C:\\Users\\Administrator\\Desktop\\Test\\"+path, "C:\\Users\\Administrator\\source\\repos\\BackgroundTest\\BackgroundTest\\Scripts\\"+ TextBox1.Text + ".pdf");
                }
            }
            public static void WordToPDF(string sourcePath, string targetPath)
            {
                Application application = new Application();
                Document document = null;
                try
                {
                    application.Visible = false;
                    document = application.Documents.Open(sourcePath);
                    document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                
            }
    
    <body>
        <form id="form1" runat="server">
            <div>
            <asp:Label ID="label1" runat="server" Text="Please enter  file names"></asp:Label>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Onclick="Button1_Click"/>
            </div>
            <div>
            <asp:Label ID="label2" runat="server" Text="Whether the file exists"></asp:Label>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </div>
            <div>
            
             <a href="<%# str%>" >Review</a>
            </div>
            <div>
                
             <a href="<%# str%>" download >Download</a>
                
            </div>
        </form>
    </body>
    

    Test33

    Best regards,
    Qi You


    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 additional answers

Sort by: Most helpful

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.