public async Task CreateFrontPageSection(string htmlPath) { try { int theID; theDoc.Rect.String = "40 70 570 700"; theID = theDoc.AddImageUrl(htmlPath); theDoc.Color.String = "0 255 0"; while (true) { if (!theDoc.Chainable(theID)) { theID = theDoc.AddImageToChain(theID); break; } theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } await Task.FromResult(0); return; } catch (Exception ex) { throw; } }
protected void Page_Load(object sender, EventArgs e) { byte[] pdfData; var url = Web.BaseUrl; using (var theDoc = new Doc()) { theDoc.MediaBox.String = "A4"; // this sets the page to A4 (also removes scrollbar showing in the pdf LOL) theDoc.TopDown = true; theDoc.Rect.Top = 5; theDoc.Rect.Left = -18; //clear caching? //theDoc.HtmlOptions.Engine = EngineType.Gecko; theDoc.HtmlOptions.PageCacheEnabled = false; theDoc.HtmlOptions.UseNoCache = true; theDoc.HtmlOptions.PageCacheClear(); theDoc.HtmlOptions.PageCachePurge(); theDoc.HtmlOptions.UseResync = true; theDoc.HtmlOptions.Timeout = 30 * 1000; // 30 seconds var id = theDoc.AddImageUrl(url); //add more pages if more than 1 page for (; theDoc.Chainable(id);) { theDoc.Page = theDoc.AddPage(); id = theDoc.AddImageToChain(id); } //theDoc.Save(fullServerPath); pdfData = theDoc.GetData(); Web.Response.ContentType = "application/pdf"; Web.Response.BinaryWrite(pdfData); theDoc.Clear(); } }
protected void BtnDownload_Click(object sender, EventArgs e) { try { // this.BtnDownload.Visible = false; // convert to PDF Doc theDoc = new Doc(); theDoc.Rect.Inset(80, 200); //theDoc.Rect.String = "50 50 550 550"; //theDoc.HtmlOptions.Engine = EngineType.Gecko; //string url = HttpContext.Current.Request.Url.Authority; string url = HttpContext.Current.Request.Url.AbsoluteUri; theDoc.AddImageUrl(url); theDoc.TextStyle.LeftMargin = 20; byte[] theData = theDoc.GetData(); StreamFileToBrowser("form.pdf", theData); } catch (Exception ex) { this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ex", "alert('" + ex.Message.ToString() + "');", true); } }
static void Main(string[] args) { System.Console.WriteLine("Enter the name of the output pdf file:"); var fileName = System.Console.ReadLine(); fileName = fileName.Replace(".pdf", ""); fileName = fileName.Replace(".PDF", ""); Doc theDoc = new Doc(); theDoc.Rect.Inset(72, 144); theDoc.HtmlOptions.AddLinks = true; int theID; theID = theDoc.AddImageUrl("http://www.yahoo.com/"); while (true) { theDoc.FrameRect(); if (!theDoc.Chainable(theID)) break; theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } theDoc.Save(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName + ".pdf")); theDoc.Clear(); }
public static void Main(string[] args) { Doc theDoc = new Doc(); theDoc.AddImageUrl("http://www.google.com/"); theDoc.Save(Server.MapPath("htmlimport.pdf")); theDoc.Clear(); }
protected void printbutton_Click(object sender, EventArgs e) { string contents = string.Empty; MemoryStream ms = new MemoryStream(); //using (StringWriter sw = new StringWriter()) { // Server.Execute("Documents/report.aspx", sw); // contents = sw.ToString(); // sw.Close(); //} try { Doc doc = new Doc(); //int font = doc.EmbedFont(Server.MapPath("Documents/") + "OpenSans-Regular-webfont.ttf", LanguageType.Unicode); //font = doc.EmbedFont(Server.MapPath("Documents/") + "OpenSans-Light-webfont.ttf", LanguageType.Unicode); doc.HtmlOptions.BrowserWidth = 960; doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; int id = 0; Random rnd = new Random(); //id = doc.AddImageUrl("http://" + Request.Url.Host + "/documents/bygg.aspx?rnd=" + rnd.Next(50000)); id = doc.AddImageUrl("http://localhost:50030/Documents/jour.aspx?rnd=" + rnd.Next(50000)); while (true) { //doc.FrameRect(); if (!doc.Chainable(id)) { break; } doc.Page = doc.AddPage(); id = doc.AddImageToChain(id); } for (int i = 0; i < doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } //doc.AddImageHtml(contents); //doc.Save(Server.MapPath("htmlimport.pdf")); doc.Save(ms); //doc.SaveOptions. doc.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename=File-{0}.pdf", 1)); Response.BinaryWrite(ms.ToArray()); Response.End(); //} } catch (Exception ex) { Response.Write(ex.Message); } }
protected void btnGenerarActas_Click(object sender, EventArgs e) { try { foreach (GridViewRow row in GridView1.Rows) { string codigo = ((Label)row.FindControl("IdCoordinacion")).Text; Coordinacion obj = DatosCoordinacion.BuscarCoordinacion(Convert.ToInt32(codigo)); //Session["CodigoObs"] = codigo; Doc documento = new Doc(); //documento.Page = documento.AddPage(); int id = 0; string url = "http://localhost:15674/InformeActasPDF.aspx" + "?CodigoObs=" + codigo + "-" + obj.Fecha; //string url = "http://localhost:15674/Constructora/InformeActa.aspx"; documento.HtmlOptions.PageCacheClear(); documento.HtmlOptions.PageCachePurge(); documento.HtmlOptions.Paged = true; documento.Page = documento.AddPage(); id = documento.AddImageUrl(url); while (true) { documento.FrameRect(); if (!documento.Chainable(id)) { break; } documento.Page = documento.AddPage(); id = documento.AddImageToChain(id); } for (int i = 1; i < documento.PageCount; i++) { documento.PageNumber = i; documento.Flatten(); } documento.Save("C:/GeneracionActas/" + codigo + ".pdf"); documento.Clear(); } } catch (Exception ex) { lblMensaje.Text = ex.Message; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { context.Response.Clear(); try { // When running as an App Service we need to install the license in code otherwise you will // get a licensing exception. ABCpdf automatically installs a trial license if no license is // found. // Your trial license may be found by uncommenting the line below WHEN RUNNING ON YOUR LOCAL // COMPUTER. NB XSettings.Key returns an empty string for purchased licenses. // throw new Exception(XSettings.Key); // Paste either the ABCpdf 12 key provided at time of purchase, or the value obtained from // uncommenting the line above. This must be set correctly prior to running on Azure. XSettings.InstallLicense("PASTE YOUR LICENSE HERE"); using (Doc doc = new Doc()) { doc.HtmlOptions.Engine = EngineType.WebKit; doc.HtmlOptions.Media = MediaType.Screen; int id = doc.AddImageUrl("https://www.websupergoo.com"); // AddImageUrl only adds the first page. The following code adds any additional pages: while (doc.Chainable(id)) { doc.Page = doc.AddPage(); id = doc.AddImageToChain(id); } // Compress output: for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } // This will ensure page is served in a web-efficient manner: doc.SaveOptions.Linearize = true; // Finally serve the page: context.Response.ContentType = "Application/Pdf"; await context.Response.BodyWriter.WriteAsync(doc.GetData()); } } catch (Exception ex) { await context.Response.WriteAsync(ex.Message); } await context.Response.CompleteAsync(); }); }); }
public static bool createPdf(long kid,string klotterno,string email) { string contents = string.Empty; MemoryStream ms = new MemoryStream(); try { int id; Doc doc = new Doc(); doc.MediaBox.String = "A4"; doc.Rect.String = doc.MediaBox.String; //doc.Rect. = doc.CropBox; doc.HtmlOptions.BrowserWidth = 980; doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; doc.HtmlOptions.ImageQuality = 33; Random rnd = new Random(); id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/klotter_pdf.aspx?id=" + kid.ToString() + "&uid="+ email +"&rnd=" + rnd.Next(50000)); while (true) { //doc.FrameRect(); if (!doc.Chainable(id)) { break; } doc.Page = doc.AddPage(); id = doc.AddImageToChain(id); } for (int i = 0; i < doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } //doc.AddImageHtml(contents); //doc.Save(Server.MapPath("htmlimport.pdf")); doc.Save(ms); //doc.SaveOptions. doc.Clear(); bool mail = Common.PdfMail(ms, email, "Klotter"); if (mail) { return AmazonHandler.PutPdfKlotter(ms, klotterno, 0); } return false; //} } catch (Exception ex) { return false; } }
/// <summary> /// Appends document with multipage content /// </summary> private void AppendChainable(Doc doc, String htmlOrUrl, Boolean isUrl = false) { Int32 blockId = isUrl ? doc.AddImageUrl(htmlOrUrl) : doc.AddImageHtml(String.Format("<html>{0}</html>", htmlOrUrl)); while (doc.Chainable(blockId)) { //doc.FrameRect(); // add a black border doc.Page = doc.AddPage(); blockId = doc.AddImageToChain(blockId); } }
protected void Page_Load(object sender, EventArgs e) { Doc theDoc = new Doc(); //theDoc.Rect.Inset(90, 150); theDoc.HtmlOptions.Engine = EngineType.Gecko; theDoc.AddImageUrl("http://google.com"); theDoc.TextStyle.LeftMargin = 50; byte[] theData = theDoc.GetData(); StreamFileToBrowser("xxx.pdf", theData); }
protected void btnPrintBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e) { int credentialID = Convert.ToInt32(Request.QueryString["credentialID"]); Doc theDoc = new Doc(); //clear caching? theDoc.HtmlOptions.PageCacheEnabled = false; theDoc.HtmlOptions.UseNoCache = true; theDoc.HtmlOptions.PageCacheClear(); theDoc.HtmlOptions.PageCachePurge(); theDoc.HtmlOptions.UseResync = true; theDoc.Rect.String = "10 90 600 750"; string selectedCriteria = Session["selectedCriteria"].ToString(); string hostURL = (HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://") + HttpContext.Current.Request.Url.Host.ToString(); string callUrl = ResolveUrl("~/Controls/Credentials/PDF/StudentCountListPdf.aspx?xCriteria=" + selectedCriteria); int theID; theID = theDoc.AddImageUrl(hostURL + callUrl); while (true) { if (!theDoc.Chainable(theID)) break; theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } theDoc = AddHeaderFooter(theDoc); byte[] pdf = theDoc.GetData(); Response.Clear(); Response.ClearHeaders(); // Add this line Response.ClearContent(); // Add this line //string filename = lblStudentName.Text.Replace(',', '-') + "EarnedCredentialList"; Response.AddHeader("Content-Disposition", "attachment; filename=" + "CredentialList" + ".pdf"); Response.AddHeader("content-length", pdf.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(pdf); Response.End(); theDoc.Clear(); }
public byte[] Convert(string link, string width, string height) { try { var theDoc = new Doc(); theDoc.SetInfo(0, "License", "141-819-141-276-8435-093"); double pageWidth = System.Convert.ToDouble(width.ToUpper().Replace("PX", "")); double pageHeight = System.Convert.ToDouble(height.ToUpper().Replace("PX", "")) * 1.762; if (pageHeight>=14400) { pageHeight = 14400; } theDoc.MediaBox.Width = pageWidth; theDoc.MediaBox.Height = pageHeight; theDoc.Rect.Width = pageWidth; theDoc.Rect.Height = pageHeight; theDoc.Rect.Inset(5, 5); theDoc.HtmlOptions.AddLinks = true; theDoc.Page = theDoc.AddPage(); var theId = theDoc.AddImageUrl(link, false, 0, true); while (true) { if (!theDoc.Chainable(theId)) break; theDoc.Page = theDoc.AddPage(); theId = theDoc.AddImageToChain(theId); } // Link pages together theDoc.HtmlOptions.LinkPages(); for (var i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } var buffer = theDoc.GetData(); theDoc.Clear(); return buffer; } catch (Exception ex) { throw ex; } }
protected void Button2_Click(object sender, EventArgs e) { //Response.Redirect("~/WebForm5.aspx"); Doc theDoc = new Doc(); //theDoc.Rect.Inset(90, 150); theDoc.HtmlOptions.Engine = EngineType.Gecko; theDoc.AddImageUrl("http://localhost/"); theDoc.TextStyle.LeftMargin = 50; byte[] theData = theDoc.GetData(); StreamFileToBrowser("xxx.pdf", theData); }
protected void PrintReport_Click(object sender, EventArgs e) { Doc theDoc = new Doc(); //HttpCookie cookie = new HttpCookie("userID", userID.ToString());//kc testing //theDoc.HtmlOptions.HttpAdditionalHeaders = "Cookie: userID=" + userID; //theDoc.HtmlOptions.NoCookie = true; theDoc.AddImageUrl("http://" + Request.Url.Authority + "/PrintableReport.aspx?userID=" + userID); byte[] theData = theDoc.GetData(); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "inline; filename=MyPDF.PDF"); Response.AddHeader("content-length", theData.Length.ToString()); Response.BinaryWrite(theData); Response.End(); }
private Stream ConvertUrlToImage(string url, int marginLeft, int marginTop, int page) { //bool isLogged = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]); MemoryStream memoryStream = null; byte[] imageBytes = null; //return the coresponding image here for the first page XSettings.InstallRedistributionLicense( System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]); //Create a new Doc using (Doc theDoc = new Doc()) { theDoc.HtmlOptions.UseScript = true; // Enable javascript at the startup time theDoc.HtmlOptions.UseActiveX = true; // Enable SVG theDoc.HtmlOptions.UseVideo = true; // Enable Video theDoc.HtmlOptions.Timeout = 120000; // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html theDoc.HtmlOptions.PageCacheEnabled = true; // Enable ABCPDF .NET page cache theDoc.Rect.Inset(marginLeft, marginTop); // Insert the margin left and margin top theDoc.Page = theDoc.AddPage(); int theID = theDoc.AddImageUrl(url.ToString()); // Now chain subsequent pages together. Stop when reach a page which wasn't truncated. while (true) { if (!theDoc.Chainable(theID)) { break; } theDoc.Page = theDoc.AddPage(); theDoc.Rendering.DotsPerInch = constDotPerInches; // set DPI = 150 theDoc.Rendering.SaveQuality = constSaveQuality; // set Quality = 100 theID = theDoc.AddImageToChain(theID); } theDoc.PageNumber = page; theDoc.Rendering.DotsPerInch = constDotPerInches; theDoc.Rendering.SaveQuality = constImageQuality; theDoc.Flatten(); imageBytes = theDoc.Rendering.GetData("abc.png"); theDoc.Clear(); } memoryStream = new MemoryStream(imageBytes); return(memoryStream); }
/// <summary> /// 整个任务书展示页面生成pdf,同时计算页码,生成书签(此方法不完善,书签定位不正确) /// </summary> /// <param name="docList"></param> /// <param name="url"></param> /// <param name="savePath"></param> /// <param name="customName"></param> /// <param name="tops"></param> /// <returns></returns> public static bool MergePdf3(List <PdfDoc> docList, string url, string savePath, string customName, Dictionary <int, int> tops) { Doc doc = new Doc(); doc.HtmlOptions.Timeout = 30 * 1000; doc.HtmlOptions.UseScript = true; doc.HtmlOptions.UseNoCache = true; doc.HtmlOptions.PageCacheEnabled = false; doc.HtmlOptions.PageCacheClear(); int num = doc.AddImageUrl(url); while (true) { if (!doc.Chainable(num)) { break; } doc.Page = doc.AddPage(); num = doc.AddImageToChain(num); } for (int i = 0; i < tops.Count; i++) { int minusOffset = tops.Values.ToList <int>()[0] * i; double offset = 0.0; doc.PageNumber = CalculatePageNum(doc, tops.Values.ToList <int>()[i], out offset, minusOffset); int id = doc.AddBookmark(GetPath(docList, tops.Keys.ToList <int>()[i]).TrimEnd('\\'), true); doc.SetInfo(id, "/Dest:Del", ""); doc.SetInfo(id, "/Dest[]:Ref", doc.Page.ToString()); doc.SetInfo(id, "/Dest[]:Name", "XYZ"); doc.SetInfo(id, "/Dest[]:Num", "0"); doc.SetInfo(id, "/Dest[]:Num", offset.ToString()); doc.SetInfo(id, "/Dest[]", "null"); } for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } doc.Save(savePath); doc.Clear(); return(true); }
public byte[] Convert(string link) { try { var theDoc = new Doc(); theDoc.MediaBox.String = "A4"; theDoc.SetInfo(0, "License", "141-819-141-276-8435-093"); theDoc.Rect.Inset(10, 5); theDoc.HtmlOptions.AddLinks = true; //theDoc.HtmlOptions.AddMovies = true; theDoc.Page = theDoc.AddPage(); theDoc.HtmlOptions.PageCacheEnabled = false; var theId = theDoc.AddImageUrl(link); while (true) { if (!theDoc.Chainable(theId)) break; theDoc.Page = theDoc.AddPage(); theId = theDoc.AddImageToChain(theId); } // Link pages together theDoc.HtmlOptions.LinkPages(); for (var i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } var buffer = theDoc.GetData(); theDoc.Clear(); return buffer; } catch (Exception ex) { throw ex; } }
/// <summary> /// CreatePDF :Public method used to create PDF file /// </summary> /// <param name="SourceFilePath">SourceFilePath Datatype:String </param> /// <param name="DestinationFilePath">DestinationFilePath Datatype:String</param> public void CreatePDF(string SourceFilePath, string DestinationFilePath) { // // Initialize required variables // string theURL = string.Empty; int theID; // // Create Pdf using the source file as input // Doc theDoc = new Doc(); //theDoc.Rect.Inset(120, 100); theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageUrl(SourceFilePath); // // Loop through and add all the html files // while (true) { theDoc.FrameRect(); // add a black border if (!theDoc.Chainable(theID)) { break; } theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } // // Now save the pdf file // theDoc.Save(DestinationFilePath); theDoc.Clear(); }
/// <summary> /// 将html页面生成pdf文档,异步方式 /// </summary> /// <param name="url"></param> /// <param name="savePath"></param> /// <returns></returns> public static bool Html2Img(string url, string originPath) { Thread newThread = new Thread(delegate() { try { Doc doc = new Doc(); doc.HtmlOptions.Timeout = 30 * 1000; doc.HtmlOptions.UseScript = true; doc.Rect.Inset(36.0, 72.0); doc.Page = doc.AddPage(); int num = doc.AddImageUrl(url); while (true) { doc.FrameRect(); if (!doc.Chainable(num)) { break; } doc.Page = doc.AddPage(); num = doc.AddImageToChain(num); } for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } doc.Save(originPath); doc.Clear(); } catch (Exception ex) { LogError.ReportErrors(ex.Message); } }); newThread.Start(); return(true); }
public static void GeneratePdf() { Doc theDoc = new Doc(); theDoc.FontSize = 96; theDoc.HtmlOptions.UseActiveX = true; theDoc.HtmlOptions.AutoTruncate = true; theDoc.HtmlOptions.Engine = EngineType.Gecko; theDoc.HtmlOptions.UseScript = true; theDoc.HtmlOptions.AddLinks = true; theDoc.HtmlOptions.AdjustLayout = false; theDoc.AddImageUrl(@"http://*****:*****@"http://localhost:5095/app/components/reports/ReportOutput.html"); theDoc.Save(@"C:\temp\testPdf.pdf"); }
static void Main(string[] args) { System.Console.WriteLine("Enter the name of the output pdf file:"); var fileName = System.Console.ReadLine(); fileName = fileName.Replace(".pdf", ""); fileName = fileName.Replace(".PDF", ""); Doc theDoc = new Doc(); theDoc.Rect.Inset(72, 144); theDoc.HtmlOptions.AddLinks = true; int theID; theID = theDoc.AddImageUrl("http://www.yahoo.com/"); while (true) { theDoc.FrameRect(); if (!theDoc.Chainable(theID)) { break; } theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } theDoc.Save(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName + ".pdf")); theDoc.Clear(); }
public void GeneratePdfForHaf(string pageurl, string fileSavePath, string corporateSurveyPdf = "", string basicBiometricFile = "", string focAttestationFile = "", string corporateCheckListPdf = "", string annualComprehensiveExamPdf = "", string memberInformationProfilePdf = "") { var finalReport = new Doc(); try { finalReport.Rect.Inset(40, 70); //pdfDoc.Rect. finalReport.MediaBox.String = PaperSize; finalReport.Rect.String = finalReport.MediaBox.String; finalReport.Page = finalReport.AddPage(); finalReport.HtmlOptions.PageCachePurge(); finalReport.HtmlOptions.Timeout = 90000; if (AllowLoadingJavascriptbeforePdfGenerate) { finalReport.HtmlOptions.UseScript = true; } int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true); while (true) { if (!finalReport.Chainable(imageToChain)) { break; } finalReport.Page = finalReport.AddPage(); imageToChain = finalReport.AddImageToChain(imageToChain); } for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++) { finalReport.PageNumber = pageNumber; //Flatten page finalReport.Flatten(); } if (!string.IsNullOrEmpty(basicBiometricFile)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(basicBiometricFile); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(corporateSurveyPdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(corporateSurveyPdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(focAttestationFile)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(focAttestationFile); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(corporateCheckListPdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(corporateCheckListPdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(annualComprehensiveExamPdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(annualComprehensiveExamPdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(memberInformationProfilePdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(memberInformationProfilePdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } finalReport.Save(fileSavePath); } catch (Exception exception) { throw exception; } finally { finalReport.Clear(); finalReport.Dispose(); } }
/// <summary> /// 按一级目录请求页面,二级和以后的目录全部不生成,书签只能定位到一级目录 /// </summary> /// <param name="docList"></param> /// <param name="savePath"></param> /// <param name="customerName"></param> /// <param name="bookTaskUrl">为a标签包含的链接</param> /// <returns></returns> public static bool MergePdf4(List <PdfDoc> docList, string savePath, string customerName, string bookTaskUrl) { if (docList.Count == 0) { return(false); } Doc doc = new Doc(); doc.HtmlOptions.Timeout = 30 * 1000; doc.HtmlOptions.UseScript = true; doc.HtmlOptions.UseNoCache = true; doc.HtmlOptions.PageCacheEnabled = false; doc.HtmlOptions.PageCacheClear(); doc.Rect.Inset(52.0, 100.0); try { Dictionary <int, string> titleDic = new Dictionary <int, string>(); foreach (PdfDoc pd in docList) { if (pd.NodePid == 0)//0为根节点,可能为封面,单独处理 { continue; } doc.Page = doc.AddPage(); doc.AddBookmark(GetPath(docList, pd).TrimEnd('\\'), pd.Expended); titleDic.Add(doc.PageCount, pd.Name); if (pd.Url == null) { continue; } int num = doc.AddImageUrl(pd.Url); while (true) { if (!doc.Chainable(num)) { break; } doc.Page = doc.AddPage(); num = doc.AddImageToChain(num); titleDic.Add(doc.PageCount, pd.Name); } } #region 添加页眉和页脚 AddHeader(ref doc, titleDic, customerName, bookTaskUrl); for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; //压缩输出 doc.Flatten(); } #endregion if (!savePath.ToLower().EndsWith(".pdf")) { savePath += ".pdf"; } doc.Save(savePath); } catch (Exception ex) { LogError.ReportErrors(ex.Message); return(false); } finally { doc.Clear(); doc.Dispose(); } return(true); }
public byte[] CreatePdf(PDFService.Settings settings) { if (settings == null) throw new ArgumentNullException("settings"); if (!settings.Uris.Any()) throw new ArgumentException("No URIs provided to create PDF from"); using (Doc pdf = new Doc()) { pdf.HtmlOptions.Engine = EngineType.Gecko; pdf.HtmlOptions.Timeout = (int)settings.Timeout.TotalMilliseconds; pdf.HtmlOptions.RetryCount = settings.RetryCount; pdf.HtmlOptions.PageCacheClear(); pdf.HtmlOptions.PageCacheEnabled = false; pdf.HtmlOptions.AddForms = settings.UseForms; pdf.HtmlOptions.AddLinks = settings.UseLinks; pdf.HtmlOptions.UseScript = settings.UseScript; pdf.Color.Red = 255; pdf.Color.Green = 255; pdf.Color.Blue = 255; pdf.Rect.Inset(10, 10); pdf.FillRect(); // If selected, make the PDF in landscape format if (settings.UseLandscapeOrientation) { pdf.Transform.Rotate(90, pdf.MediaBox.Left, pdf.MediaBox.Bottom); pdf.Transform.Translate(pdf.MediaBox.Width, 0); pdf.Rect.Width = pdf.MediaBox.Height; pdf.Rect.Height = pdf.MediaBox.Width; } int imageId = 0; // For each URI provided, add the result to the output doc foreach (String uri in settings.Uris) { if (imageId != 0) { pdf.Page = pdf.AddPage(); } // Render the web page by uri and return the image id for chaining imageId = pdf.AddImageUrl(uri, paged: true, width: 0, disableCache: false); while (true) { // Stop when we reach a page which wasn't truncated, per the examples if (!pdf.Chainable(imageId)) break; // Add a page to the pdf and sets the page id pdf.Page = pdf.AddPage(); // Add the previous image to the chain and set the image id imageId = pdf.AddImageToChain(imageId); } } // flatten the pages for (var ii = 1; ii <= pdf.PageCount; ii++) { pdf.PageNumber = ii; pdf.Flatten(); } // Return the byte array representing the pdf return pdf.GetData(); } }
//public static bool PageToPdfByteArray(string url, string path, Encoding encoe) //{ // byte[] pdfBuf; // bool ret = false; // try // { // GlobalConfig gc = new GlobalConfig(); // // set it up using fluent notation // gc.SetMargins(new Margins(0, 0, 0, 0)) // .SetDocumentTitle("Test document") // .SetPaperSize(PaperKind.A4); // //... etc // // create converter // IPechkin pechkin = new SynchronizedPechkin(gc); // // subscribe to events // //pechkin.Begin += OnBegin; // //pechkin.Error += OnError; // //pechkin.Warning += OnWarning; // //pechkin.PhaseChanged += OnPhase; // //pechkin.ProgressChanged += OnProgress; // //pechkin.Finished += OnFinished; // // create document configuration object // ObjectConfig oc = new ObjectConfig(); // // and set it up using fluent notation too // oc.SetCreateExternalLinks(false) // .SetFallbackEncoding(encoe) // .SetLoadImages(true) // .SetPageUri(url); // //... etc // // convert document // pdfBuf = pechkin.Convert(oc); // FileStream fs = new FileStream(path, FileMode.Create); // fs.Write(pdfBuf, 0, pdfBuf.Length); // fs.Close(); // ret = true; // } // catch (Exception ex) // { // } // return ret; //} /// <summary> /// 根据页面url,按节点目录生成pdf和对应书签(空页面不生成) /// </summary> /// <param name="docList"></param> /// <param name="savePath"></param> /// <returns></returns> public static bool MergePdf(List <PdfDoc> docList, string savePath) { if (docList.Count == 0) { return(false); } Doc doc = new Doc(); doc.HtmlOptions.Timeout = 30 * 1000; doc.HtmlOptions.UseScript = true; doc.Rect.Inset(36.0, 72.0);//Rect默认是文档整个页面大小, 这里的Inset表示将Rect左右留出36的空白,上下留出72的空白 string emptyMarkPath = null; bool emptyMarkExp = false; try { foreach (PdfDoc pd in docList) { if (pd.NodePid != 0) //0为根节点,没有页面 { if (string.IsNullOrEmpty(pd.Url)) { /** * 有些目录可能没有页面内容,这里则先将目录的bookmark路径保存; * **/ emptyMarkPath = GetPath(docList, pd).TrimEnd('\\'); emptyMarkExp = pd.Expended; } else { doc.Page = doc.AddPage(); if (emptyMarkPath != null) { doc.AddBookmark(emptyMarkPath, emptyMarkExp); //让空目录指定到其第一个子页面 emptyMarkPath = null; //添加之后置空 } doc.AddBookmark(GetPath(docList, pd).TrimEnd('\\'), pd.Expended); int num = doc.AddImageUrl(pd.Url); while (true) { //doc.FrameRect();//给内容区域添加黑色边框 if (!doc.Chainable(num)) { break; } doc.Page = doc.AddPage(); num = doc.AddImageToChain(num); } } } } for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } if (!savePath.ToLower().EndsWith(".pdf")) { savePath += ".pdf"; } doc.Save(savePath); } catch (Exception ex) { LogError.ReportErrors(ex.Message); return(false); } finally { doc.Clear(); doc.Dispose(); } return(true); }
protected void PrintReport_Click(object sender, EventArgs e) { Doc theDoc = new Doc(); //HttpCookie cookie = new HttpCookie("userID", userID.ToString());//kc testing //theDoc.HtmlOptions.HttpAdditionalHeaders = "Cookie: userID=" + userID; //theDoc.HtmlOptions.NoCookie = true; theDoc.AddImageUrl("http://"+Request.Url.Authority+"/PrintableReport.aspx?userID=" + userID); byte[] theData = theDoc.GetData(); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "inline; filename=MyPDF.PDF"); Response.AddHeader("content-length", theData.Length.ToString()); Response.BinaryWrite(theData); Response.End(); }
// Put license key to Azure setting. #region IPrintServiceV1 Members /// <summary> /// Convert the HTML code from the specified URL to a PDF document and send the /// document as an attachment to the browser /// </summary> /// <param name="sessionTokenId">SessionTokenId given by user to authorize</param> /// <param name="url">The URL of a page that will be rendered</param> /// <param name="marginLeft"></param> /// <param name="marginTop"></param> /// <returns>a byte array that rendered as a PDF, will be null if error</returns> Stream IPrintServiceV1.ConvertUrlToPdf(string sessionTokenId, string url, int marginLeft, int marginTop) { Stream returnStream = null; if (marginLeft < 10000 && marginTop < 10000) { try { bool isQualified = IsQualifiedUrl(url.ToString()); if (isQualified) { // Create a Doc object XSettings.InstallRedistributionLicense(licenseKey); using (Doc theDoc = new Doc()) { //theDoc.SetInfo(0, "RenderDelay", "1000"); theDoc.HtmlOptions.UseScript = true; theDoc.HtmlOptions.UseActiveX = true; theDoc.HtmlOptions.UseVideo = true; theDoc.HtmlOptions.PageCacheEnabled = true; theDoc.HtmlOptions.Timeout = 120000; // 120 seconds theDoc.Rect.Inset(marginLeft, marginTop); // add margin // Add the first page of HTML. Save the returned ID as this will be used to add subsequent pages theDoc.Page = theDoc.AddPage(); int theID = theDoc.AddImageUrl(url.ToString()); // Now chain subsequent pages together. Stop when reach a page which wasn't truncated. while (true) { if (!theDoc.Chainable(theID)) { break; } theDoc.Page = theDoc.AddPage(); theDoc.Rendering.DotsPerInch = constDotPerInches; // DPI theDoc.Rendering.SaveQuality = constSaveQuality; // Quality theID = theDoc.AddImageToChain(theID); } // After adding the pages we can flatten them. We can't do this until after the pages have been added // because flattening will invalidate our previous ID and break the chain. for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } // Get pdf data from the Doc object returnStream = new MemoryStream(theDoc.GetData()); //returnByte = theDoc.GetData(); theDoc.Clear(); } } //TO-DO: Add the HTTP Status Code 403 (Forbidden) when the url is not in supported list } catch (UriFormatException uriFormatException) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, uriFormatException.StackTrace, HttpUtility.UrlEncode(url.ToString()) + uriFormatException.Message + uriFormatException.StackTrace); returnStream = null; } catch (WebException webException) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, webException.StackTrace, HttpUtility.UrlEncode(url.ToString()) + webException.Message + webException.StackTrace); returnStream = null; } catch (Exception ex) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, HttpUtility.UrlEncode(url.ToString()) + ex.Message + ex.StackTrace); returnStream = null; } if (WebOperationContext.Current != null) { WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf"; HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl; WebOperationContext.Current.OutgoingResponse.Headers.Add(cacheHeader, string.Format(CultureInfo.InvariantCulture, "max-age={0}, must-revalidate", CachingDuration)); //Add one day caching } } return(returnStream); }
/// <summary> /// 将html页面生成pdf文档,同步方式 /// </summary> /// <param name="url"></param> /// <param name="savePath"></param> /// <returns></returns> public static bool Html2PDFSynch(string url, string savePath, string customName) { Doc doc = new Doc(); try { //url = "http://localhost:8018/PDF?returnUrl=http://localhost:8018/Material/MatList/exporttopdf?matListId=167"; doc.HtmlOptions.UseNoCache = true; doc.HtmlOptions.PageCacheEnabled = false; doc.HtmlOptions.PageCacheClear(); doc.HtmlOptions.Timeout = 30 * 1000; doc.HtmlOptions.UseScript = true; doc.HtmlOptions.UseActiveX = true; doc.Rect.Inset(36.0, 72.0); doc.Page = doc.AddPage(); int num = doc.AddImageUrl(url); while (true) { //doc.FrameRect();//添加黑色边框 if (!doc.Chainable(num)) { break; } doc.Page = doc.AddPage(); num = doc.AddImageToChain(num); } for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; doc.Color.String = "0 0 0"; //黑色 doc.AddLine(24, 750, 588, 750); //画一条分隔线 doc.Rect.String = "24 12 588 40"; doc.HPos = 0; doc.VPos = 0.5; doc.Font = doc.AddFont("宋体", "ChineseS"); doc.TextStyle.Italic = true; doc.AddHtml(" <font color=\"#cccccc\">" + customName + "</font>"); doc.TextStyle.Italic = false; doc.Rect.String = "24 12 588 40"; doc.HPos = 1.0; doc.VPos = 0.5; doc.Color.String = "0 0 0"; //黑色 doc.AddHtml("page " + i.ToString() + "/" + doc.PageCount.ToString()); doc.AddLine(24, 40, 588, 40); doc.Flatten(); } if (!savePath.ToLower().EndsWith(".pdf")) { savePath += ".pdf"; } doc.Save(savePath); doc.Clear(); return(true); } catch (Exception ex) { LogError.ReportErrors(ex.Message); return(false); } finally { doc.Clear(); } return(true); }
private Stream ConvertUrlToImage(string url, int marginLeft, int marginTop, int page) { //bool isLogged = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]); MemoryStream memoryStream = null; byte[] imageBytes = null; //return the coresponding image here for the first page XSettings.InstallRedistributionLicense( System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]); //Create a new Doc using (Doc theDoc = new Doc()) { theDoc.HtmlOptions.UseScript = true; // Enable javascript at the startup time theDoc.HtmlOptions.UseActiveX = true; // Enable SVG theDoc.HtmlOptions.UseVideo = true; // Enable Video theDoc.HtmlOptions.Timeout = 120000; // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html theDoc.HtmlOptions.PageCacheEnabled = true; // Enable ABCPDF .NET page cache theDoc.Rect.Inset(marginLeft, marginTop); // Insert the margin left and margin top theDoc.Page = theDoc.AddPage(); int theID = theDoc.AddImageUrl(url.ToString()); // Now chain subsequent pages together. Stop when reach a page which wasn't truncated. while (true) { if (!theDoc.Chainable(theID)) break; theDoc.Page = theDoc.AddPage(); theDoc.Rendering.DotsPerInch = constDotPerInches; // set DPI = 150 theDoc.Rendering.SaveQuality = constSaveQuality; // set Quality = 100 theID = theDoc.AddImageToChain(theID); } theDoc.PageNumber = page; theDoc.Rendering.DotsPerInch = constDotPerInches; theDoc.Rendering.SaveQuality = constImageQuality; theDoc.Flatten(); imageBytes = theDoc.Rendering.GetData("abc.png"); theDoc.Clear(); } memoryStream = new MemoryStream(imageBytes); return memoryStream; }
public static string ConvertHtmlToPDF(string filePathHTML) { WriteLog("[ConvertHmlToPDF_CreateFile]: ----------Begin----------"); WriteLog("[ConvertHmlToPDF_CreateFile] filePathHTML: " + filePathHTML); string result = string.Empty; bool rsCheck = XSettings.InstallLicense("X/VKS08wmMtAun4hGNvFONzmS/QQY7hZ9Z2488LHIg8X5nu5Qx7dYsZhez00hWZRXd5Xim0uoXp3ifxwDtAusQ0lPTnPXR1401Y="); if (!rsCheck) { result = "Invalid Websupergoo license."; WriteLog("[ConvertHmlToPDF_CreateFile] result: " + result); return(null); } string FilesDir = Functions.GetAppConfigByKey("FileDir"); if (!System.IO.File.Exists(FilesDir)) { System.IO.Directory.CreateDirectory(FilesDir); } string fileName = "File_Convert_PDF" + DateTime.Now.Ticks.ToString() + ".pdf"; string fullPath = Path.Combine(FilesDir, fileName); WriteLog("[ConvertHmlToPDF_CreateFile] FilesDir: " + FilesDir); WriteLog("[ConvertHmlToPDF_CreateFile] fileName: " + fileName); WriteLog("[ConvertHmlToPDF_CreateFile] fullPath: " + fullPath); #region Create PDF try { Doc pages = new Doc(); try { Doc doc = new Doc(); //doc.Rect.Inset(30, 10); //doc.HtmlOptions.Engine = EngineType.MSHtml; //doc.HtmlOptions.Engine = EngineType.Chrome; doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; doc.HtmlOptions.BrowserWidth = 1200; doc.HtmlOptions.PageCacheClear(); doc.HtmlOptions.UseScript = true; //doc.HtmlOptions.OnLoadScript = "(function(){window.ABCpdf_go = false; setTimeout(function(){window.ABCpdf_go = true;}, 3000);})();"; // Render after 3 seconds //doc.HtmlOptions.OnLoadScript = " (function(){" // + " window.external.ABCpdf_RenderWait();" // + " setTimeout(function(){ " // + " window.external.ABCpdf_RenderComplete(); }, 10000);" // + "})();"; //doc.SetInfo(0, "RenderDelay", "45000"); //doc.SetInfo(0, "OneStageRender", 0); //Render after 3 seconds //doc.HtmlOptions.OnLoadScript = "(function(){" // + " window.ABCpdf_go = false;" // + " setTimeout(function(){ window.ABCpdf_go = true; }, 10000);" // + "})();"; doc.Page = doc.AddPage(); int theID; theID = doc.AddImageUrl(filePathHTML); while (true) { doc.FrameRect(); // add a black border if (!doc.Chainable(theID)) { break; } doc.Page = doc.AddPage(); theID = doc.AddImageToChain(theID); System.Threading.Thread.Sleep(500); } //doc.Rect.String = "100 50 500 150"; //for (int i = 1; i <= doc.PageCount; i++) //{ // doc.PageNumber = i; // doc.AddText("Page " + i.ToString()); // //doc.FrameRect(); //} pages.Append(doc); } catch (Exception ex2) { result = ex2.Message; WriteLog("[ConvertHmlToPDF_CreateFile] - Exception: " + result); return(null); } pages.Save(fullPath); pages.Clear(); result = fullPath; WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); return(result); } catch (Exception ex) { result = ex.Message; WriteLog("[ConvertHmlToPDF_CreateFile] -- Exception: " + result); return(null); } #endregion }
public String gerarRelatorioPDF(string cdaEmpCadastro, string cpfCnpj, string cdaQuestionarioEmpresa, string protocolo, string estado, string categoria, Boolean comentarios, Int32 programaId, Int32 turmaId, Int32 avaliador, Int32 intro, Boolean EnviaEmail, Page page) { if (avaliador == 0) { new BllQuestionarioEmpresa().AlterarSomenteFlagLeitura(StringUtils.ToInt(cdaQuestionarioEmpresa), true); } Session.Timeout = 13000; Server.ScriptTimeout = 13000; string caminhoFisicoRelatorios = ConfigurationManager.AppSettings["caminhoFisicoRelatorios"]; string caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio"]; try { string[] files = Directory.GetFiles(caminhoFisicoRelatorios); foreach (string file in files) { if (!File.GetCreationTime(file).ToShortDateString().Equals(DateTime.Now.ToShortDateString())) { File.Delete(file); } } } catch { } string c = ""; try { int chave = 0; if (comentarios) { chave = 1; } //if (programaId == 3) //{ // caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2008"]; //} //else if (programaId == 4) //{ // caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorio2009"]; //} //else if (programaId == 7) //{ // caminhoPaginaRelatorio = ConfigurationManager.AppSettings["caminhoPaginaRelatorioAutoavaliacao"]; //} Doc theDoc = new Doc(); theDoc.SetInfo(0, "License", "bc8b5c07da69df2b6c476901f513aa8b89ff6d8ce56a16797802be20da7348078ab9ae58bd6c483b"); theDoc.HtmlOptions.Timeout = 30000000; String link = this.getDominio(page) + caminhoPaginaRelatorio + "?CDA_EMP_CADASTRO=" + cdaEmpCadastro + "&TX_CPF_CNPJ=" + cpfCnpj + "&Chave=" + chave + "&Avaliador=" + avaliador + "&Intro=" + intro + "&CEA_QUESTIONARIO_EMPRESA=" + cdaQuestionarioEmpresa + "&Protocolo=" + protocolo + "&turmaId=" + turmaId + "&programaId=" + programaId; if (estado != null) { link = link + "&naoMostraComentarioJuiz=1"; } else if (page.Request["naoMostraComentarioJuiz"] != null && page.Request["naoMostraComentarioJuiz"].Equals("1")) { link = link + "&naoMostraComentarioJuiz=1"; } int theID = theDoc.AddImageUrl(link, true, 1000, true); while (true) { theDoc.FrameRect(); if (!theDoc.Chainable(theID)) { break; } theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } String ArquivoNome = protocolo + "_" + DateTime.Now.Ticks + ".pdf"; String CaminhoPDF = caminhoFisicoRelatorios + ArquivoNome; CaminhoPDF = Server.MapPath(CaminhoPDF); theDoc.Save(CaminhoPDF); theDoc.HtmlOptions.PageCacheClear(); theDoc.Clear(); theDoc.Delete(theID); theDoc.Dispose(); theDoc = null; GC.Collect(); Thread.Sleep(5000); if (EnviaEmail) { //WebUtils.EnviaEmail(Request.QueryString["EmailContato"], "Relatório de AutoAvaliação", new System.Text.StringBuilder(), CaminhoPDF); return(CaminhoPDF); //ClientScript.RegisterClientScriptBlock(Page.GetType(), "closeWindow", "window.close();", true); } else { //Response.Redirect(getDominio(this.Page) + "/Relatorios/" + ArquivoNome); //return null; return("/Relatorios/" + ArquivoNome); } } catch (Exception ex) { //Response.Write(ex.ToString()); throw ex; } return(null); }
/// <summary> /// Convert the HTML code from the specified URL to a PDF document and send the /// document as an attachment to the browser /// </summary> /// <param name="sessionTokenId">SessionTokenId given by user to authorize</param> /// <param name="url">The URL of a page that will be rendered</param> /// <param name="marginLeft"></param> /// <param name="marginTop"></param> /// <returns>a byte array that rendered as a PDF, will be null if error</returns> Stream IPrintServiceV1.ConvertUrlToPdf(string sessionTokenId, string url, int marginLeft, int marginTop) { Stream returnStream = null; if (marginLeft < 10000 && marginTop < 10000) { try { bool isQualified = IsQualifiedUrl(url.ToString()); if (isQualified) { // Create a Doc object XSettings.InstallRedistributionLicense(licenseKey); using (Doc theDoc = new Doc()) { //theDoc.SetInfo(0, "RenderDelay", "1000"); theDoc.HtmlOptions.UseScript = true; theDoc.HtmlOptions.UseActiveX = true; theDoc.HtmlOptions.UseVideo = true; theDoc.HtmlOptions.PageCacheEnabled = true; theDoc.HtmlOptions.Timeout = 120000; // 120 seconds theDoc.Rect.Inset(marginLeft, marginTop); // add margin // Add the first page of HTML. Save the returned ID as this will be used to add subsequent pages theDoc.Page = theDoc.AddPage(); int theID = theDoc.AddImageUrl(url.ToString()); // Now chain subsequent pages together. Stop when reach a page which wasn't truncated. while (true) { if (!theDoc.Chainable(theID)) break; theDoc.Page = theDoc.AddPage(); theDoc.Rendering.DotsPerInch = constDotPerInches; // DPI theDoc.Rendering.SaveQuality = constSaveQuality; // Quality theID = theDoc.AddImageToChain(theID); } // After adding the pages we can flatten them. We can't do this until after the pages have been added // because flattening will invalidate our previous ID and break the chain. for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } // Get pdf data from the Doc object returnStream = new MemoryStream(theDoc.GetData()); //returnByte = theDoc.GetData(); theDoc.Clear(); } } //TO-DO: Add the HTTP Status Code 403 (Forbidden) when the url is not in supported list } catch (UriFormatException uriFormatException) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, uriFormatException.StackTrace, HttpUtility.UrlEncode(url.ToString()) + uriFormatException.Message + uriFormatException.StackTrace); returnStream = null; } catch (WebException webException) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, webException.StackTrace, HttpUtility.UrlEncode(url.ToString()) + webException.Message + webException.StackTrace); returnStream = null; } catch (Exception ex) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; LoggerHelperV1.Error(AssemblyName, AssemblyVersion, Environment.MachineName, ex.StackTrace, HttpUtility.UrlEncode(url.ToString()) + ex.Message + ex.StackTrace); returnStream = null; } if (WebOperationContext.Current != null) { WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf"; HttpResponseHeader cacheHeader = HttpResponseHeader.CacheControl; WebOperationContext.Current.OutgoingResponse.Headers.Add(cacheHeader, string.Format(CultureInfo.InvariantCulture, "max-age={0}, must-revalidate", CachingDuration)); //Add one day caching } } return returnStream; }
private int GetNumberOfPages(string url, string extension, int marginLeft, int marginTop) { this.margineLeft = marginLeft; this.margineTop = marginTop; this.url = url; int PageCount = 0; bool isLogged = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]); // This code line sets the license key to the Doc object XSettings.InstallRedistributionLicense(System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]); //Create a new Doc switch (extension) { //If the url is a pdf file case PDF: byte[] buffer = new byte[4096]; int count = 0; byte[] pdfBytes = null; using (MemoryStream memoryStream = new MemoryStream()) { WebRequest webRequest = WebRequest.Create(url); WebResponse webResponse = webRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); do { count = stream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, count); } while (count != 0); pdfBytes = memoryStream.ToArray(); } using (Doc theDoc = new Doc()) { theDoc.HtmlOptions.UseScript = true; theDoc.HtmlOptions.UseActiveX = true; theDoc.HtmlOptions.UseVideo = true; theDoc.HtmlOptions.PageCacheEnabled = true; theDoc.HtmlOptions.Timeout = 120000; theDoc.Rect.Inset(marginLeft, marginTop); theDoc.Read(pdfBytes); PageCount = theDoc.PageCount; } return(PageCount); //break; default: using (Doc htmlDoc = new Doc()) { //Start new thread to generate images when user call GetNumberOfPages method htmlDoc.HtmlOptions.UseScript = true; // Enable javascript at the startup time htmlDoc.HtmlOptions.UseActiveX = true; // Enable SVG htmlDoc.HtmlOptions.UseVideo = true; // Enable Video htmlDoc.HtmlOptions.Timeout = 120000; // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html htmlDoc.HtmlOptions.PageCacheEnabled = true; // Enable ABCPDF .NET page cache htmlDoc.Rect.Inset(marginLeft, marginTop); // Insert the margin left and margin top htmlDoc.Page = htmlDoc.AddPage(); int theID = htmlDoc.AddImageUrl(url.ToString()); // Now chain subsequent pages together. Stop when reach a page which wasn't truncated. while (true) { if (!htmlDoc.Chainable(theID)) { break; } htmlDoc.Page = htmlDoc.AddPage(); htmlDoc.Rendering.DotsPerInch = constDotPerInches; // set DPI = 150 htmlDoc.Rendering.SaveQuality = constSaveQuality; // set Quality = 100 theID = htmlDoc.AddImageToChain(theID); } if (htmlDoc != null) { return(htmlDoc.PageCount); } } break; } return(0); }
/// <summary> /// When a Level A User clicks finish several things occur: /// <list type="bullet"> /// <item>The status of the cart is changed to submitted.</item> /// <item>The name of the cart is changed so that new carts can be created with the cart's name.</item> /// <item>An email is sent out informing the user that the cart was submitted.</item> /// </list> /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSubmitCart_Click(object sender, EventArgs e) { //This only occurs for Level A USERS //Generate Confirmation Number string webConfirmationNumber = NWTD.Orders.Cart.GenerateOrderNumber(this.CheckoutCart); //Set the Confirmation Number on the cart this.CheckoutCart["WebConfirmation"] = webConfirmationNumber; //Save Confirmation # to cart so it can be used by CheckoutSummaryPrint for PDF (Heath Gardner 08/19/13) //NOTE: Must do save here before changing status and cart name. Otherwise cart won't be found for CheckoutSummaryPrint (hg) this.SaveChanges(); //Set cart status to SUBMITTED this.CheckoutCart.Status = NWTD.Orders.Cart.CART_STATUS.SUBMITTED.ToString(); //change the name of the cart so future carts with the same name can be created this.CheckoutCart.Name = this.CheckoutCart.Name + "_" + this.CheckoutCart.Id; //The following two lines have been moved to above, so we can not only generate the number but SAVE it as well (Heath Gardner 08/19/13) //string webConfirmationNumber = NWTD.Orders.Cart.GenerateOrderNumber(this.CheckoutCart); //generate a confirmation numbmer //this.CheckoutCart["WebConfirmation"] = webConfirmationNumber; //set the confirmation number on the cart //Create the Order Summary pdf via abcPDF using (var doc = new Doc()) { doc.HtmlOptions.Media = MediaType.Print; //Heath Gardner Replaced below "AddImageUrl" code to work with multiple page documents per WebSuperGoo's documentation //doc.AddImageUrl(string.Format("{0}/checkout/ordersummaryprint.aspx?cart={1}&uid={2}&IsLevelA={3}", // GetHost(), Request["cart"], ProfileContext.Current.UserId, // NWTD.Profile.CurrentUserLevel.Equals(NWTD.UserLevel.A))); ////////Beginning of Added functionality to "inset", create mulitple page PDFs, and to "flatten" the PDF (Heath Gardner 03/22/13) int docID; //Inset doc object edges so PDF Margins are acceptable (HG 03/22/13) doc.Rect.Inset(30, 30); //Create the first page and save the docID (HG 03/22/13) //Added 'true' to end of AddImageUrl call to "disable cache". Fixes duplicate PDF issue (Heath Gardner 03/22/13) docID = doc.AddImageUrl(string.Format("{0}/checkout/ordersummaryprint.aspx?cart={1}&uid={2}&IsLevelA={3}", GetHost(), Request["cart"], ProfileContext.Current.UserId, NWTD.Profile.CurrentUserLevel.Equals(NWTD.UserLevel.A)), true, 0, true); //Chain the subsequent pages together. Stop when we reach a page that is not truncated (HG 03/22/13) while (true) { doc.FrameRect(); if (!doc.Chainable(docID)) { break; } doc.Page = doc.AddPage(); docID = doc.AddImageToChain(docID); } //Flatten each page of the PDF document per abcPDF's best practices (HG 03/22/13) for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } ////////End of of Added functionality to "inset", create mulitple page PDFs, and to "flatten" the PDF (Heath Gardner 03/22/13) doc.Save(Server.MapPath(string.Format("~/Orders/{0}.pdf", webConfirmationNumber))); doc.Clear(); } this.SaveChanges(); //save the cart //send the email try { //we won't be converting to a PurchaseOrder anymore. Keep it as a cart, change the cart's status. //this.CheckoutCart.OrderNumberMethod = new Mediachase.Commerce.Orders.Cart.CreateOrderNumber(NWTD.Orders.Cart.GenerateOrderNumber); //this._puchaseOrder = this.CheckoutCart.SaveAsPurchaseOrder(); try { this.SendConfirmationEmail(); } catch (Exception ex) { this.OrderMessage.Text += string.Format("Your order was submitted, however there was a problem sending your confirmation email: {0}", ex.Message); } } catch (Exception ex) { this.OrderMessage.Text += string.Format("There was an error creating a purchase order: {0}", ex.Message); } //indicate that the order is complete this.ShowOrderComplete(); //Response.Redirect(NavigationManager.GetUrl("OrderThanks")); }
protected void btnPrintBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e) { Doc theDoc = new Doc(); //clear caching? theDoc.HtmlOptions.PageCacheEnabled = false; theDoc.HtmlOptions.UseNoCache = true; theDoc.HtmlOptions.PageCacheClear(); theDoc.HtmlOptions.PageCachePurge(); theDoc.HtmlOptions.UseResync = true; theDoc.Rect.String = "20 90 580 750"; string hostURL = (HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://") + HttpContext.Current.Request.Url.Host.ToString(); string callUrl = ResolveUrl("~/Controls/Credentials/PDF/CredentialListPdf.aspx"); int theID; theID = theDoc.AddImageUrl(hostURL + callUrl); while (true) { if (!theDoc.Chainable(theID)) break; theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } theDoc = AddHeaderFooter(theDoc); byte[] pdf = theDoc.GetData(); Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment; filename=" + "CredentialList" + ".pdf"); Response.AddHeader("content-length", pdf.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(pdf); Response.End(); }
private int GetNumberOfPages(string url, string extension, int marginLeft, int marginTop) { this.margineLeft = marginLeft; this.margineTop = marginTop; this.url = url; int PageCount = 0; bool isLogged = Boolean.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[constLog]); // This code line sets the license key to the Doc object XSettings.InstallRedistributionLicense(System.Web.Configuration.WebConfigurationManager.AppSettings[constLicenseKey]); //Create a new Doc switch (extension) { //If the url is a pdf file case PDF: byte[] buffer = new byte[4096]; int count = 0; byte[] pdfBytes = null; using (MemoryStream memoryStream = new MemoryStream()) { WebRequest webRequest = WebRequest.Create(url); WebResponse webResponse = webRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); do { count = stream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, count); } while (count != 0); pdfBytes = memoryStream.ToArray(); } using (Doc theDoc = new Doc()) { theDoc.HtmlOptions.UseScript = true; theDoc.HtmlOptions.UseActiveX = true; theDoc.HtmlOptions.UseVideo = true; theDoc.HtmlOptions.PageCacheEnabled = true; theDoc.HtmlOptions.Timeout = 120000; theDoc.Rect.Inset(marginLeft, marginTop); theDoc.Read(pdfBytes); PageCount = theDoc.PageCount; } return PageCount; //break; default: using (Doc htmlDoc = new Doc()) { //Start new thread to generate images when user call GetNumberOfPages method htmlDoc.HtmlOptions.UseScript = true; // Enable javascript at the startup time htmlDoc.HtmlOptions.UseActiveX = true; // Enable SVG htmlDoc.HtmlOptions.UseVideo = true; // Enable Video htmlDoc.HtmlOptions.Timeout = 120000; // Time out is 2 minutes for ABCPDF .NET Doc calls the url to get the html htmlDoc.HtmlOptions.PageCacheEnabled = true; // Enable ABCPDF .NET page cache htmlDoc.Rect.Inset(marginLeft, marginTop); // Insert the margin left and margin top htmlDoc.Page = htmlDoc.AddPage(); int theID = htmlDoc.AddImageUrl(url.ToString()); // Now chain subsequent pages together. Stop when reach a page which wasn't truncated. while (true) { if (!htmlDoc.Chainable(theID)) break; htmlDoc.Page = htmlDoc.AddPage(); htmlDoc.Rendering.DotsPerInch = constDotPerInches; // set DPI = 150 htmlDoc.Rendering.SaveQuality = constSaveQuality; // set Quality = 100 theID = htmlDoc.AddImageToChain(theID); } if (htmlDoc != null) return htmlDoc.PageCount; } break; } return 0; }
public static ResponseVal ConvertHmlToPDF(string QuoteISN, string StaffISN) { Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------Begin----------"); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: QuoteISN: " + QuoteISN); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: StaffISN: " + StaffISN); ResponseVal resVal = new ResponseVal(); var result = -1; //bool rsCheck = XSettings.InstallLicense("X/VKS08wmMtAun4hGNvFONzmS/QQY7hZ9Z2488LHIg8X5nu5Qx7dYsZhez00hWZRXd5Xim0uoXp3ifxwDtAusQ0lPTnPXR1401Y="); //bool rsCheck = XSettings.InstallLicense("XeJREBodo/8B4nxZb63WaYOgeuQZPdtypqn27rLhKmkRz3CDGnvCaco3Dn5c5nQFBw=="); //bool rsCheck = XSettings.InstallLicense("XeJREBodo/8B7XFQaf2CPdzyKuccPdtypszj/8HiXH0n+nieP1jmdZIuAHpU7kIFBw=="); //bool rsCheck = XSettings.InstallLicense("X/VKS0cNn5FipytaG9r2LN6gO9YNAb8f0JfhndPDLmJ14X+2ABmFVcU9cz81hwBrU4M7olk+wz9WgdFFKeN5mjkhfR3iZgJkr1Y="); bool rsCheck = XSettings.InstallLicense(Functions.GetConfig_CS("AbcPdfLicense")); if (!rsCheck) { resVal.Code = -1; resVal.Msg = "Invalid Websupergoo license."; return(resVal); } var ds = Globals.DB.ExecuteQuery(string.Format("select MemberISN from Vw_SolarQuote where QuoteISN={0}", Functions.ConvertObjectToInt(QuoteISN))); if (Functions.IsEmpty(ds)) { resVal.Code = -1; resVal.Data = null; resVal.Msg = "QuoteISN is missing"; Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: Msg: " + resVal.Msg); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); return(resVal); } var row = ds.Tables[0].Rows[0]; var MemberISN = row["MemberISN"].ToString(); string url = string.Format("{0}/Proposal.aspx?isn={1}&staffisn={2}", Functions.GetConfig_CS("AdminURL").TrimEnd('/'), QuoteISN, StaffISN); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] -- url: " + url); string Temp = Functions.GetConfig_CS("TemporaryDir"); string outputPath = HttpContext.Current.Server.MapPath("~/OutputFiles/Pdf"); string sFileName = ""; string sFullPathTemp = ""; #region Create PDF try { Doc pages = new Doc(); try { Doc doc = new Doc(); //doc.Rect.Inset(30, 10); //doc.HtmlOptions.Engine = EngineType.MSHtml; //doc.HtmlOptions.Engine = EngineType.Chrome; //doc.HtmlOptions.Engine = EngineType.MSHtml; //doc.SetInfo(0, "RenderDelay", "500"); //doc.SetInfo(0, "OneStageRender", 0); doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; doc.HtmlOptions.BrowserWidth = 1200; doc.HtmlOptions.PageCacheClear(); doc.HtmlOptions.UseScript = true; //doc.HtmlOptions.OnLoadScript = "(function(){window.ABCpdf_go = false; setTimeout(function(){window.ABCpdf_go = true;}, 3000);})();"; // Render after 3 seconds //doc.HtmlOptions.OnLoadScript = " (function(){" // + " window.external.ABCpdf_RenderWait();" // + " setTimeout(function(){ " // + " window.external.ABCpdf_RenderComplete(); }, 5000);" // + "})();"; //doc.SetInfo(0, "RenderDelay", "5000"); //doc.SetInfo(0, "OneStageRender", 0); //Render after 3 seconds //doc.HtmlOptions.OnLoadScript = "(function(){" // + " window.ABCpdf_go = false;" // + " setTimeout(function(){ window.ABCpdf_go = true; }, 10000);" // + "})();"; doc.Page = doc.AddPage(); int theID; theID = doc.AddImageUrl(url); while (true) { doc.FrameRect(); // add a black border if (!doc.Chainable(theID)) { break; } doc.Page = doc.AddPage(); theID = doc.AddImageToChain(theID); System.Threading.Thread.Sleep(500); } //doc.Rect.String = "100 50 500 150"; //for (int i = 1; i <= doc.PageCount; i++) //{ // doc.PageNumber = i; // doc.AddText("Page " + i.ToString()); // //doc.FrameRect(); //} pages.Append(doc); } catch (Exception ex2) { resVal.Code = -1; resVal.Data = null; resVal.Msg = ex2.Message; Globals.WriteLog("[ConvertHmlToPDF_CreateFile] - Exception: " + ex2.Message); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); return(resVal); } if (!System.IO.File.Exists(Temp)) { System.IO.Directory.CreateDirectory(Temp); } Globals.WriteLog("[ConvertHmlToPDF_CreateFile] Temp: " + Temp); sFileName = "Proposal_" + DateTime.Now.Ticks.ToString() + ".pdf"; sFullPathTemp = Path.Combine(Temp, sFileName); pages.Save(sFullPathTemp); pages.Clear(); string sDocName = "Proposal_" + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second; result = (int)Globals.DB.ExecuteStoredProc("xp_debtext_documenttask_insupd", new string[] { "DocumentISN", "docFileName", "docName", "docType", "docPublic", "MemberISN" }, new object[] { 0, sFileName, sDocName, "Proposal", 1, MemberISN }); var sPathFileDoc = Path.Combine(Functions.GetConfig_CS("FilesDir"), GetDocumentsPath(result, null)); if (!System.IO.File.Exists(sPathFileDoc)) { System.IO.Directory.CreateDirectory(sPathFileDoc); } var sFileSave = Path.Combine(sPathFileDoc, sFileName); File.Copy(sFullPathTemp, sFileSave); //File.Delete(sFullPathTemp); resVal.Code = 1; resVal.Data = result; resVal.Msg = "Success"; Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sFullPathTemp: " + sFullPathTemp); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sPathFileDoc: " + sFileSave); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sFileName: " + sFileName); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] DocumentISN: " + result); } catch (Exception ex) { resVal.Code = -1; resVal.Data = null; resVal.Msg = ex.Message; Globals.WriteLog("[ConvertHmlToPDF_CreateFile] -- Exception: " + ex.Message); } Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); #endregion #region old // string fileName = DateTime.Now.Ticks + ".pdf"; // string pathFileName = Path.Combine(Functions.GetConfig_CS("TemporaryDir"), fileName); // string ContentHtml = ReadFromFile(pathFileHtml); // //StringBuilder sb = new StringBuilder(); // //sb.Append(ContentHtml); // //var css = ContentHtml.Substring(ContentHtml.IndexOf("<style>") + 7, ContentHtml.IndexOf("</style>") - 7 - ContentHtml.IndexOf("<style>")); //// var js = ContentHtml.Substring(ContentHtml.IndexOf("<script>") + 8, ContentHtml.IndexOf("</script>") - 8 - ContentHtml.IndexOf("<script>")); // StringReader sr = new StringReader(ContentHtml); // //StringWriter sw = new StringWriter(); // //HtmlTextWriter hw = new HtmlTextWriter(sw); // //hw.Write(ContentHtml); // Document pdfDoc = new Document(PageSize.A4); // //HTMLWorker htmlparser = new HTMLWorker(pdfDoc); // using (MemoryStream memoryStream = new MemoryStream()) // { // PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); // pdfDoc.Open(); // //htmlparser.Parse(new StringReader(sw.ToString())); // ////HTMLWorker.ParseToList(sr, new StyleSheet()); // //pdfDoc.Close(); // //StyleSheet ss = new StyleSheet(); // //ArrayList list = HTMLWorker.ParseToList(new StringReader(ContentHtml), ss); // //foreach (IElement e in list) // //{ // // pdfDoc.Add(e); // // // //using (TextReader sReader = new StringReader(ContentHtml.ToString())) // //{ // // ArrayList list = HTMLWorker.ParseToList(sReader, new StyleSheet()); // // foreach (IElement elm in list) // // { // // pdfDoc.Add(elm); // // } // //} // //pdfDoc.HtmlStyleClass = ContentHtml; // //pdfDoc.JavaScript_onLoad = ContentHtml; // //htmlparser.Parse(sr); // // step 5 // //Image img = Image.GetInstance(ContentHtml); // //pdfDoc.Add(img); // //writer.AddJavaScript(ContentHtml); // iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr); // //using (var srHtml = new StringReader(ContentHtml)) // //{ // // //Parse the HTML // // iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, srHtml); // //} // //using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) // //{ // // using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(ContentHtml))) // // { // // Parse the HTML // // iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, msHtml, msCss); // // } // //} // pdfDoc.Close(); // byte[] bytes = memoryStream.ToArray(); // //BinaryFormatter bf = new BinaryFormatter(); // //MemoryStream ms = new MemoryStream(); // //bf.Serialize(ms, ContentHtml); // //bytes = ms.ToArray(); // pathFileName = pathFileName + ".pdf"; // System.IO.File.WriteAllBytes(pathFileName, bytes); // memoryStream.Close(); // File.Copy(Path.Combine(Functions.GetConfig_CS("TemporaryDir"), fileName + ".pdf"), Path.Combine(Functions.GetConfig_CS("FilesConvertPdf"), fileName + ".pdf"), true); // resVal.Code = 1; // resVal.Data = pathFileName; // resVal.Msg = "Success"; // } #endregion return(resVal); }
protected void printbutton_Click(object sender, EventArgs e) { //if (pdf_synced) { //} else { string contents = string.Empty; MemoryStream ms = new MemoryStream(); try { Doc doc = new Doc(); doc.MediaBox.String = "A4"; doc.HtmlOptions.BrowserWidth = 980; doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; doc.HtmlOptions.ImageQuality = 33; int id = 0; Random rnd = new Random(); id = doc.AddImageUrl("http://" + Request.Url.Host + "/Documents/jour_pdf.aspx?id=" + jourid.ToString() + "&rnd=" + rnd.Next(50000)); while (true) { //doc.FrameRect(); if (!doc.Chainable(id)) { break; } doc.Page = doc.AddPage(); id = doc.AddImageToChain(id); } doc.Rect.String = "10 780 595 840"; doc.HPos = 0.5; doc.VPos = 0.0; doc.Color.String = "0 255 0"; doc.FontSize = 36; for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; id = doc.AddImageUrl("http://" + Request.Url.Host + "/Documents/header.aspx?id=" + jourid.ToString() +"&rnd=" + rnd.Next(50000)); } doc.Rect.String = "10 0 585 100"; doc.HPos = 0.5; doc.VPos = 1.0; //doc.FontSize = 36; //for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = 1; id = doc.AddImageUrl("http://" + Request.Url.Host + "/Documents/footer.aspx?rnd=" + rnd.Next(50000)); //doc.AddText("Page " + i.ToString() + " of " + doc.PageCount.ToString()); //doc.FrameRect(); //} for (int i = 0; i < doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } //doc.AddImageHtml(contents); //doc.Save(Server.MapPath("htmlimport.pdf")); doc.Save(ms); //doc.SaveOptions. doc.Clear(); bool success = AmazonHandler.PutPdfJour(ms, journo); if (success) { Response.Write("SUCCESS!!!!"); } else { Response.Write("FAIL!!!!"); } //} } catch (Exception ex) { Response.Write(ex.Message); } //} }
private void CreatePDFFetched(EngineType engine) { var connectionString = ConfigurationManager.ConnectionStrings["LicenseKey"].ConnectionString; XSettings.InstallLicense(connectionString); var theDoc = new Doc(); theDoc.HtmlOptions.Engine = engine; theDoc.HtmlOptions.UseScript = false; theDoc.HtmlOptions.BrowserWidth = 800; theDoc.HtmlOptions.ForGecko.UseScript = false; theDoc.Rendering.DotsPerInch = 300; theDoc.HtmlOptions.ForGecko.InitialWidth = 800; theDoc.Rect.Inset(18, 18); theDoc.Page = theDoc.AddPage(); int theID = theDoc.AddImageUrl("http://woot.com/", true, 800, true); while (true) { theDoc.FrameRect(); // add a black border if (!theDoc.Chainable(theID)) break; theDoc.Page = theDoc.AddPage(); theID = theDoc.AddImageToChain(theID); } for (int i = 1; i <= theDoc.PageCount; i++) { theDoc.PageNumber = i; theDoc.Flatten(); } Response.Buffer = false; Response.AddHeader("Content-Disposition", "inline; filename=\"rept.pdf\""); Response.ContentType = "application/pdf"; theDoc.Save(Response.OutputStream); Response.Flush(); }
public static bool createPdf(long jid,string journo,string email) { string contents = string.Empty; MemoryStream ms = new MemoryStream(); try { int id; Doc doc = new Doc(); doc.MediaBox.String = "A4"; doc.HtmlOptions.BrowserWidth = 980; doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; doc.HtmlOptions.ImageQuality = 33; Random rnd = new Random(); id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/jour_pdf.aspx?id=" + jid.ToString() + "&uid="+ email +"&rnd=" + rnd.Next(50000)); while (true) { //doc.FrameRect(); if (!doc.Chainable(id)) { break; } doc.Page = doc.AddPage(); id = doc.AddImageToChain(id); } doc.Rect.String = "10 780 595 840"; doc.HPos = 0.5; doc.VPos = 0.0; doc.Color.String = "0 255 0"; doc.FontSize = 36; for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = i; id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/header.aspx?id=" + jid.ToString() + "&rnd=" + rnd.Next(50000)); } doc.Rect.String = "10 0 585 100"; doc.HPos = 0.5; doc.VPos = 1.0; //doc.FontSize = 36; //for (int i = 1; i <= doc.PageCount; i++) { doc.PageNumber = 1; id = doc.AddImageUrl("http://" + HttpContext.Current.Request.Url.Host + "/Documents/footer.aspx?rnd=" + rnd.Next(50000)); //doc.AddText("Page " + i.ToString() + " of " + doc.PageCount.ToString()); //doc.FrameRect(); //} for (int i = 0; i < doc.PageCount; i++) { doc.PageNumber = i; doc.Flatten(); } //doc.AddImageHtml(contents); //doc.Save(Server.MapPath("htmlimport.pdf")); doc.Save(ms); //doc.SaveOptions. doc.Clear(); bool mail = Common.PdfMail(ms, email); if (mail) { return AmazonHandler.PutPdfJour(ms, journo); } return false; //} } catch (Exception ex) { return false; } }
public void GeneratePdf(string pageurl, string fileSavePath, bool showFooterText = false, string footerText = "", string coverSheetPages = "", string customizedLetter = "", string contentpages = "", string kynFile = "", string bloodLetter = "", string doctorLetter = "", string corporateFluffLetter = "", bool isPpCustomer = false, string awvTestResult = "", bool isPcpReport = false, bool generatePcpLetter = false, string scannedDocumentsPdf = "", string eawvPdfReport = "", string focAttestation = "", string attestationForm = "", bool hasSectionToDisplay = true, string mammogram = "", string ifobt = "", string urineMicroalbumin = "", string participantLetter = "", string chlamydia = "", string awvBoneMass = "", string osteoporosis = "", string quantaFloAbi = "", string hkyn = "", string mybioCheckAssessment = "", string memberLetter = "", string greenFormAttestation = "", string dpn = "") { var finalReport = new Doc(); int prePrintedCount = 0; var beforFinalReportDoc = new Doc(); try { if (coverSheetPages != "") { var participantLetterDoc = new Doc(); var doctorLetterDoc = new Doc(); var customizedLetterDoc = new Doc(); var contentpagesDoc = new Doc(); var eawvPdfDoc = new Doc(); var memberLetterDoc = new Doc(); var greenFormAttestationDoc = new Doc(); try { //Cover Sheet beforFinalReportDoc.Read(coverSheetPages); if (!string.IsNullOrWhiteSpace(greenFormAttestation)) { greenFormAttestationDoc.Read(greenFormAttestation); beforFinalReportDoc.Append(greenFormAttestationDoc); } //Member Letter if (!string.IsNullOrEmpty(memberLetter)) { memberLetterDoc.Read(memberLetter); beforFinalReportDoc.Append(memberLetterDoc); } if (!string.IsNullOrEmpty(participantLetter)) { participantLetterDoc.Read(participantLetter); beforFinalReportDoc.Append(participantLetterDoc); } //Doctor letter if (!string.IsNullOrEmpty(doctorLetter)) { doctorLetterDoc.Read(doctorLetter); beforFinalReportDoc.Append(doctorLetterDoc); } //Customized Letter Hospital Partner no default letter if (!string.IsNullOrEmpty(customizedLetter)) { customizedLetterDoc.Read(customizedLetter); beforFinalReportDoc.Append(customizedLetterDoc); } if (!string.IsNullOrEmpty(contentpages)) { contentpagesDoc.Read(contentpages); beforFinalReportDoc.Append(contentpagesDoc); } if (!string.IsNullOrEmpty(eawvPdfReport)) { eawvPdfDoc.Read(eawvPdfReport); beforFinalReportDoc.Append(eawvPdfDoc); } prePrintedCount = beforFinalReportDoc.PageCount; } catch (Exception exception) { throw exception; } finally { participantLetterDoc.Clear(); participantLetterDoc.Dispose(); doctorLetterDoc.Clear(); doctorLetterDoc.Dispose(); customizedLetterDoc.Clear(); customizedLetterDoc.Dispose(); contentpagesDoc.Clear(); contentpagesDoc.Dispose(); eawvPdfDoc.Clear(); eawvPdfDoc.Dispose(); memberLetterDoc.Clear(); memberLetterDoc.Dispose(); greenFormAttestationDoc.Clear(); greenFormAttestationDoc.Dispose(); } } if (hasSectionToDisplay) { finalReport.Rect.Inset(40, 70); //pdfDoc.Rect. finalReport.MediaBox.String = PaperSize; finalReport.Rect.String = finalReport.MediaBox.String; finalReport.Page = finalReport.AddPage(); finalReport.HtmlOptions.PageCachePurge(); finalReport.HtmlOptions.Timeout = 90000; if (AllowLoadingJavascriptbeforePdfGenerate) { finalReport.HtmlOptions.UseScript = true; } int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true); while (true) { if (!finalReport.Chainable(imageToChain)) { break; } finalReport.Page = finalReport.AddPage(); imageToChain = finalReport.AddImageToChain(imageToChain); } footerText = string.IsNullOrEmpty(footerText) ? string.Empty : footerText + " | "; int pageCount = finalReport.PageCount + prePrintedCount; for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++) { finalReport.PageNumber = pageNumber; if (showFooterText) { int pNum = pageNumber + prePrintedCount; string txt = footerText + "Page: " + pNum + " of " + pageCount; finalReport.Color.String = "0 0 0"; //Dark grey text finalReport.TextStyle.VPos = 0.98; finalReport.TextStyle.HPos = (pageNumber % 2) == 0 ? 0.10 : 0.80; finalReport.AddFont("Arial"); //Add the page number finalReport.AddText(txt); //Add a line above page number finalReport.AddLine(21, 40, 590, 40); } //Flatten page finalReport.Flatten(); } } if (!string.IsNullOrEmpty(kynFile)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(kynFile); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } AppendPdf(finalReport, hkyn); if (!string.IsNullOrEmpty(bloodLetter)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(bloodLetter); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(corporateFluffLetter)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(corporateFluffLetter); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(awvTestResult)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(awvTestResult); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(scannedDocumentsPdf)) { var inputScannedPdfDoc = new Doc(); try { inputScannedPdfDoc.Read(scannedDocumentsPdf); finalReport.Append(inputScannedPdfDoc); } finally { inputScannedPdfDoc.Clear(); inputScannedPdfDoc.Dispose(); } } AppendPdf(finalReport, focAttestation); AppendPdf(finalReport, attestationForm); AppendPdf(finalReport, mammogram); AppendPdf(finalReport, ifobt); AppendPdf(finalReport, urineMicroalbumin); AppendPdf(finalReport, chlamydia); AppendPdf(finalReport, awvBoneMass); AppendPdf(finalReport, osteoporosis); AppendPdf(finalReport, quantaFloAbi); AppendPdf(finalReport, mybioCheckAssessment); AppendPdf(finalReport, dpn); if (coverSheetPages != "") { try { beforFinalReportDoc.Append(finalReport); beforFinalReportDoc.Save(fileSavePath); } catch (Exception exception) { throw exception; } } else { finalReport.Save(fileSavePath); } } catch (Exception exception) { throw exception; } finally { finalReport.Clear(); finalReport.Dispose(); beforFinalReportDoc.Clear(); beforFinalReportDoc.Dispose(); } }