public FileStreamResult GeneraPDF(string Documento, string RIF, string Titulo, string URL) { // create global configuration object GlobalConfig gc = new GlobalConfig(); // set it up using fluent notation gc.SetMargins(new Margins(50, 50, 0, 0)) .SetDocumentTitle(Titulo) .SetPaperSize(PaperKind.Letter); //... etc // create converter IPechkin pechkin = new SynchronizedPechkin(gc); // create document configuration object ObjectConfig oc = new ObjectConfig(); // and set it up using fluent notation too oc.SetCreateExternalLinks(false) .SetFallbackEncoding(Encoding.ASCII) .SetLoadImages(true) .SetPageUri(URL.Replace("GeneraPDF", "")); //... etc // convert document byte[] pdfBuf = pechkin.Convert(oc); HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + Titulo + " " + Documento + ".pdf"); MemoryStream ms = new MemoryStream(pdfBuf); return(new FileStreamResult(ms, "application/pdf")); }
//html to Pdf public static void HtmlToPdf(string filePath, string html, bool isOrientation = false) { if (string.IsNullOrEmpty(html)) { html = "Null"; } // 创建全局信息 GlobalConfig gc = new GlobalConfig(); gc.SetMargins(new Margins(50, 50, 60, 60)) .SetDocumentTitle("MarkWord") .SetPaperSize(PaperKind.A4) .SetPaperOrientation(isOrientation) .SetOutlineGeneration(true); //页面信息 ObjectConfig oc = new ObjectConfig(); oc.SetCreateExternalLinks(false) .SetFallbackEncoding(Encoding.UTF8) .SetLoadImages(true) .SetScreenMediaType(true) .SetPrintBackground(true); //.SetZoomFactor(1.5); var pechkin = new SimplePechkin(gc); pechkin.Finished += Pechkin_Finished; pechkin.Error += Pechkin_Error; pechkin.ProgressChanged += Pechkin_ProgressChanged; var buf = pechkin.Convert(oc, html); if (buf == null) { Common.ShowMessage("导出异常"); return; } try { string fn = filePath; //Path.GetTempFileName() + ".pdf"; FileStream fs = new FileStream(fn, FileMode.Create); fs.Write(buf, 0, buf.Length); fs.Close(); //Process myProcess = new Process(); //myProcess.StartInfo.FileName = fn; //myProcess.Start(); } catch { } }
private void SaveHtmlAsPdf(string fName, string html) { GlobalConfig cfg = new GlobalConfig(); SimplePechkin sp = new SimplePechkin(cfg); ObjectConfig oc = new ObjectConfig(); oc.SetCreateExternalLinks(true) .SetFallbackEncoding(Encoding.ASCII) .SetLoadImages(true) .SetAllowLocalContent(true) .SetPrintBackground(true); byte[] pdfBuf = sp.Convert(oc, "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title></title></head><body>" + html + "</body></html>"); FileStream fs = new FileStream(fName, FileMode.Create, FileAccess.ReadWrite); foreach (var byteSymbol in pdfBuf) { fs.WriteByte(byteSymbol); } fs.Close(); }
static void Main(string[] args) { Thread.CurrentThread.SetApartmentState(ApartmentState.STA); maxTreadNumber = int.Parse(ConfigurationManager.AppSettings["MaxThreadNumber"].ToString()); string[] paras = args[0].Split(','); environment = paras[0]; switch (environment) { case "1": environment = "DEV"; break; case "2": environment = "QA"; break; case "3": environment = "UAT"; break; case "4": environment = "PROD"; break; default: break; } // get data from databases string connetionStr = ConfigurationManager.ConnectionStrings["SQL" + environment].ConnectionString; string cmd = "SELECT [ID],[Control_ID],[Claim_Number],[Claimant_Number],[Form_ID],[sequence],[FormName] ,[URL],[URLDate],[URLFlag],[AttachmentName],[PDFName],[PDFDate] ,[Processed] FROM test where id> (1591748 +" + (1000 * int.Parse(paras[1])).ToString() + ") and id<=(1591748 +" + (1000 * int.Parse(paras[1]) + 1000).ToString() + ")";// [TRANSFORMDB].[dbo].[CMT_ASPX_to_PDF_URL]"; using (SqlConnection sc = new SqlConnection(connetionStr)) { SqlCommand scmd = new SqlCommand(cmd, sc); try { sc.Open(); SqlDataAdapter sda = new SqlDataAdapter(scmd); DataSet sd = new DataSet(); sda.Fill(sd); dataRowQueue = new ConcurrentQueue <DataRow>(sd.Tables[0].AsEnumerable().ToList <DataRow>()); sda.Dispose(); } catch (Exception e) { throw e; } } //get the html contents while (threadNumber < maxTreadNumber) { //control thread amount threadNumber++; var thread = getWebBrowerThread(); //thread.SetApartmentState(ApartmentState.STA); thread.Start(); } Console.WriteLine("started"); while (dataRowQueue != null && dataRowQueue.Count > 0 && htmlQueue.Count == 0) { Thread.Sleep(1000); } while (pdfThreadNumber < maxTreadNumber) { pdfThreadNumber++; Thread pdfThread = new Thread(() => { GlobalConfig gc = new GlobalConfig(); gc.SetMargins(new Margins(100, 100, 100, 100)); gc.SetPaperSize(PaperKind.Letter); IPechkin pechkin = new SimplePechkin(gc); ObjectConfig configuration = new ObjectConfig(); configuration.SetCreateExternalLinks(true).SetFallbackEncoding(Encoding.UTF8).SetLoadImages(true).SetCreateForms(false); /*test error*/ int m = 0; /*end*/ while (htmlQueue.Count != 0) { //while(threadNumber>=maxTreadNumber) // { // Thread.Sleep(1000); // } /*test error*/ m++; if (m == 50) { throw (new Exception("forced")); } /*end*/ while (dataRowQueue != null && dataRowQueue.Count > 0 && htmlQueue.Count == 0) { Thread.Sleep(1000); } /*isProcessDone = false; * var subThread = new Thread(() => * {*/ //threadNumber++; DataRow dr; if (htmlQueue.TryDequeue(out dr)) { rounds++; try { byte[] pdfBuf = pechkin.Convert(configuration, dr["URL"].ToString()); var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "testpdf\\" + dr["Claim_Number"].ToString() + "_" + dr["Claimant_Number"].ToString() + "_" + dr["Form_ID"].ToString() + "_" + dr["sequence"].ToString() + ".pdf"); System.IO.File.WriteAllBytes(testFile, pdfBuf); pdfBuf = null; dr.Delete(); dr = null; testFile = null; } catch (Exception e) { MessageBox.Show(e.Message); } if (rounds % 1000 == 0) { GC.Collect(); GC.WaitForPendingFinalizers(); } } Application.ApplicationExit += Application_PDFApplicationExit; Application.ExitThread(); Application.Exit(); } }); pdfThread.Start(); } }