C # free solution for generating PDF files from HTML code

Source: Internet
Author: User

Recently, I developed a project to generate PDF files from HTML code. Therefore, I searched the internet for several days, rejected the solutions one by one, and finally found a free solution.

Jiangsq12345 original MIBA. For more information, see http://blog.csdn.net/jiangsq12345/article/details/7615974,4. Thank you!

Preparations
  • Install office2007 or later
  • Install the 2007 Microsoft Office Add-on: Microsoft save as PDF or XPS,

The idea of this solution is very simple, divided into two steps (calling the office word2007 Control)

  1. Save the HTML code as an HTML file
  2. Open the HTML file and save it as a PDF file.

First, import the database

I will share with you the main source code below, hoping to help the compatriots who are facing the problem

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. text; using system. io; using Microsoft. office. interOP. word; namespace file receiving and receiving system {public class pdffacloud {private string datetime = datetime. now. tostring ("yyyy-mm-dd hh: mm: SS "). replace (":", ""); Private httpserverutility Server = NULL; private string path_pdf = NULL; private string path_html = NULL; private stri Ng html_content = NULL; private string partition _name = NULL; private string path_word = NULL; Microsoft. office. interOP. word. application mywordapp = new Microsoft. office. interOP. word. applicationclass (); /// <summary> /// convert the HTML code into a PDF file and save it. /// </Summary> /// <Param name = "server"> server </Param> /// <Param name = "content"> HTML code </param> /// <Param name = "name"> pdf file name </param> Public pdffacloud (httpse Rverutility S, string content, string name) {Server = s; pai_name = Name; path_pdf = server. mappath (siteconf. path_pdfs + "\" + partition _name + ". PDF "); path_html = server. mappath (siteconf. path_tmp_html + "\" + datetime + ". html "); html_content = content; // check and create the system folder createdirectory (siteconf. path_pdfs); createdirectory (siteconf. path_tmp_html); createdirectory (siteconf. path_tmp_word);} public pdffac Centers (httpserverutility S, string word_name) {Server = s; path_word = server. mappath (siteconf. path_tmp_word + "\" + word_name + ". doc "); path_pdf = server. mappath (siteconf. path_pdfs + "\" + word_name + ". PDF "); // check and create the system folder createdirectory (siteconf. path_pdfs); createdirectory (siteconf. path_tmp_html); createdirectory (siteconf. path_tmp_word);} // <summary> // start conversion // </Summary> // <Param name = "Type"> type of the converted original file: HTML/word </param> // <Param name = "type"> if it is a word type, specify the path </param> Public void start (siteconf. doctype type, string word_path) {Switch (type) {Case siteconf. doctype. HTML: createhtml (string) path_html, html_content); convert2pdf (path_html); break; Case siteconf. doctype. word: convertword2pdf (path_word, path_pdf); break; default: If (siteconf. debug) console. write ("[note] the file type is incorrect! "); Break ;}} /// <summary> /// Save the HTML code to the HTML file /// </Summary> /// <Param name = "FILENAME"> path of the HTML file to be saved </param> // <Param name = "content"> content string of the HTML file to be written </param> Public void createhtml (string filename, string content) {// read the HTML template page to the stringbuilder object // string [] format = new string [4]; // define the array with the same number of htmlyem tags. Try {stringbuilder htmltext = new stringbuilder (); htmltext. append (html_content); Using (strea Mwriter Sw = new streamwriter (filename, false, system. text. encoding. getencoding ("gb2312") // Save the address {SW. writeline (htmltext); Sw. flush (); Sw. close ();} GC. collect (); GC. waitforpendingfinalizers ();} catch (exception excep) {If (siteconf. debug) console. write (excep. message) ;}}/// <summary> // convert the HTML file content to word and save it (remove the hmtl tag) /// </Summary> private void converthtml2word (Object filename) {try {object Nothing = system. reflection. missing. value; object missing = system. type. missing; object confirmconversions = false; object readonly = true; object addtorecentfiles = false; object passworddocument = missing; object passwordtemplate = missing; object revert = missing; object writepassworddocument = missing; object writepasswordtemplate = missing; object format = missing; // object encoding = missin G; object visible = missing; object openandrepair = missing; object documentdirection = missing; object noencodingdialog = missing; object xmltransform = missing; object fileformat = Microsoft. office. interOP. word. wdsaveformat. wdformatdocument; object savenativepictureformat = false; object lineending = Microsoft. office. interOP. word. wdlineendingtype. wdcrlf; // word. wdlineendingtype. wdlsps; Microsoft. Office. interOP. word. applicationclass owordapp = new applicationclass (); Microsoft. office. interOP. word. document oworddoc = owordapp. documents. add (ref nothing, ref nothing); oworddoc = owordapp. documents. open (ref filename, ref confirmconversions, ref readonly, ref addtorecentfiles, ref passworddocument, ref passwordtemplate, ref revert, ref writepassworddocument, ref writep Asswordtemplate, ref format, ref encoding, ref visible, ref openandrepair, ref documentdirection, ref noencodingdialog, ref xmltransform); // Save the content of the worddoc object as oworddoc. saveas (ref filename, ref fileformat, ref nothing, ref nothing, ref addtorecentfiles, ref nothing, ref savenativepictureformat, ref nothing, ref nothing, ref nothing, ref line Ending, ref nothing); // closes the worddoc object oworddoc. close (ref nothing, ref nothing, ref nothing); // close the owordapp component object. quit (ref nothing, ref nothing, ref nothing);} catch (exception excep) {If (siteconf. debug) console. write (excep. message );}} /// <summary> /// convert HTML to PDF /// </Summary> /// <Param name = "FILENAME"> path and name of the file to be read </ param> private void convert2pdf (Object filename) {applicationclass W Ordapplication = new applicationclass (); wordapplication. visible = false; document worddocument = NULL; object parammissing = type. missing; wdexportformat paramexportformat = wdexportformat. wdexportformatpdf; bool paramopenafterexport = false; wdexportoptimizefor paramexportoptimizefor = wdexportoptimizefor. wdexportoptimizeforprint; wdexportrange paramexportrange = wdexportrange. wdexportalldocumen T; int paramstartpage = 0; int paramendpage = 0; wdexportitem paramexportitem = wdexportitem. wdexportdocumentcontent; bool paramincludedocprops = true; bool paramkeepsert = true; wdexportcreatebookmarks paramcreatebookmarks = wdexportcreatebookmarks. wdexportcreatewordbookmarks; bool paramdocstructuretags = true; bool parambitmapmissingfonts = true; bool paramuseiso19005_1 = false; try {// open Source Document. worddocument = wordapplication. documents. open (ref filename, ref parammissing, ref parammissing, ref parammissing, ref parammissing); // export it in the specified format. if (worddocu Ment! = NULL) worddocument. parameters (path_pdf, paramexportformat, parameters, parameters, paramexportrange, paramstartpage, paramendpage, paramexportitem, parameters, paramkeepsert, paramcreatebookmarks, parameters, ref parammissing);} catch (exception excep) {If (siteconf. debug) console. write (excep. message );} Finally {// close and release the document object. If (worddocument! = NULL) {worddocument. Close (ref parammissing, ref parammissing, ref parammissing); worddocument = NULL;} // quit word and release the applicationclass object. If (wordapplication! = NULL) {wordapplication. Quit (ref parammissing, ref parammissing, ref parammissing); wordapplication = NULL ;}/// if (! Siteconf. debug) // deletefile (string) filename); GC. collect (); GC. waitforpendingfinalizers ();}} /// <summary> /// convert Word to PDF /// </Summary> /// <Param name = "word_filename"> DOC file path </param> // /<Param name = "pdf_filename"> pdf storage path </param> private void convertword2pdf (Object word_filename, object pai_filename) {applicationclass wordapplication = new applicationclass (); wordapplication. visible = false; Document worddocument = NULL; object parammissing = type. missing; wdexportformat paramexportformat = wdexportformat. wdexportformatpdf; bool paramopenafterexport = false; wdexportoptimizefor paramexportoptimizefor = wdexportoptimizefor. wdexportoptimizeforprint; wdexportrange paramexportrange = wdexportrange. wdexportalldocument; int paramstartpage = 0; int paramendpage = 0; wdexportitem paramexpor Titem = wdexportitem. wdexportdocumentcontent; bool paramincludedocprops = true; bool paramkeepsert = true; wdexportcreatebookmarks paramcreatebookmarks = wdexportcreatebookmarks. wdexportcreatewordbookmarks; bool paramdocstructuretags = true; bool parambitmapmissingfonts = true; bool paramuseiso19005_1 = false; try {// open the source document. worddocument = wordapplication. documents. open (ref wor D_filename, ref parammissing, ref parammissing, ref parammissing, ref parammissing, ref parammissing); // export it in the specified format. if (worddocument! = NULL) worddocument. parameters (string) pai_filename, paramexportformat, parameters, parameters, paramexportrange, paramstartpage, paramendpage, paramexportitem, parameters, paramkeepsert, paramcreatebookmarks, paramdocstructuretags, parameters, parameters, ref parammissing );} catch (exception excep) {If (siteconf. debug) console. write (E Xcep. Message);} finally {// close and release the document object. If (worddocument! = NULL) {worddocument. Close (ref parammissing, ref parammissing, ref parammissing); worddocument = NULL;} // quit word and release the applicationclass object. If (wordapplication! = NULL) {wordapplication. quit (ref parammissing, ref parammissing, ref parammissing); wordapplication = NULL;} GC. collect (); GC. waitforpendingfinalizers (); GC. collect (); GC. waitforpendingfinalizers ();}} /// <summary> /// Delete the specified file /// </Summary> /// <Param name = "FILENAME"> specify the physical path and name of the file </param> private void deletefile (string filename) {If (file. exists (server. mappath (string) filename) file. delete (Server. mappath (string) filename); else if (siteconf. debug) console. write ("file [" + filename + "] does not exist ");} /// <summary> /// check and create the specified folder /// </Summary> /// <Param name = "path"> folder virtual path </param> private void createdirectory (string path) {If (! Directory. exists (server. mappath (PATH) {directory. createdirectory (server. mappath (PATH ));}}}}

The biggest advantage of this solution is that it is free of charge and supports any language.
The disadvantage is that every time the server creates a PDF file, it needs to call the word control (especially for file read/write operations). Therefore, it consumes a lot of system resources, so it is not suitable for large websites. I suggest you spend thousands of RMB to buy one that supports Chinese characters.

Thank you for your suggestions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.