C: generate Pdf with TuesPechkin

1, demand

Some time ago, there was a demand to generate pdf from the web page. After finding various plug-ins, I decided to use this TuesPechkin, which is generated by C code in the background

2. Practice

What I want to do is to make a relatively simple page, use MVC binding, dynamic data loading, give a button on the page, click and request the background interface, then pdf file can be generated

3. Implementation mode

Introduce two related DLLs, TuesPechkin.Wkhtmltox.XXX, and select the corresponding DLLs according to your current system (usually add the first two),


4. Generate PDF snippet

First, the specified HTML page is generated into a string string in the background, and then the following method is called.

        /// <summary>
        //Generate pdf
        /// </summary>
        ///< param name = "htmlstr" > generate content < / param >
        ///< param name = "path" > generate address < / param >
        private static void ConvertHtmlTextToPdf(string htmlStr, string filepath)
            if (!Directory.Exists(filepath))  //Folder does not exist, create
                Directory.CreateDirectory(filepath);  //Create a new folder

            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".pdf";
            var path = filepath + fileName;
            var document = new HtmlToPdfDocument
                GlobalSettings =
                    ProduceOutline = true,
                    DocumentTitle = "Title",
                    PaperSize = PaperKind.A4, // Implicit conversion to PechkinPaperSize
                    Margins =
                        Unit = Unit.Centimeters
                Objects =
                    new ObjectSettings
                        HtmlText =htmlStr,
                        WebSettings =new WebSettings

            byte[] buf = GetConverter().Convert(document);
            //Write the result binary data directly to the file stream
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            fs.Write(buf, 0, buf.Length);
            IToolset toolset = new PdfToolset();

5, remarks

This plug-in is friendly to css style support, but does not support the use of external style sheets. It must be embedded style, and the overall layout of Pdf generated is too small. You need to fine tune the style and be careful

6. Here's the final rendering

Tags: C#

Posted on Thu, 16 Apr 2020 07:18:41 -0700 by Confusion101