//******************************************************************************************** // //******************************************************************************************** public ActionResult PrintPDF(int id) { // read parameters from the webpage string url = Request.Url.Authority + Request.ApplicationPath + "/Quotes/QuoteDetailsPDF/" + id; // instantiate a html to pdf converter object SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf(); // set converter options converter.Options.PdfPageSize = SelectPdf.PdfPageSize.A4; converter.Options.PdfPageOrientation = SelectPdf.PdfPageOrientation.Portrait; //converter.Options.WebPageWidth = webPageWidth; //converter.Options.WebPageHeight = webPageHeight; // create a new pdf document converting an url SelectPdf.PdfDocument doc = converter.ConvertUrl(url); // save pdf document byte[] pdf = doc.Save(); // close pdf document doc.Close(); // return resulted pdf document FileResult fileResult = new FileContentResult(pdf, "application/pdf"); fileResult.FileDownloadName = "Document.pdf"; return(fileResult); //return RedirectToAction("QuoteDetails/" + id); }
// This event handler is where the time-consuming work is done. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; SelectPdf.HtmlToPdf converter = InitConverter(); int count = 0; if (string.IsNullOrEmpty(folderStoragePath)) { string exePath = Application.ExecutablePath; folderStoragePath = Path.Combine(exePath.Remove(exePath.LastIndexOf('\\')), "funix-certificate"); } try { foreach (DataGridViewRow row in dataGridView1.Rows) { //TODO: (Ms.Hồng Anh required) File excel change the column Tên chứng chỉ (tiếng anh) and Chứng chỉ to single column Mã môn. //check if row has checked in check box if (!backgroundWorker1.CancellationPending && Convert.ToBoolean(row.Cells["checkBoxColumn"].Value)) { //render this row to pdf string studentName = row.Cells["Họ và tên"].Value.ToString(); string studentId = row.Cells["Mã sinh viên"].Value.ToString(); string email = row.Cells["Email"].Value.ToString(); DateTime date = Convert.ToDateTime(row.Cells["Ngày hoàn thành "].Value); string ccVnName = row.Cells["Tên chứng chỉ"].Value.ToString().Trim(); if (ccVnName.StartsWith("Chứng chỉ ")) { ccVnName = ccVnName.Replace("Chứng chỉ ", "").Trim(); ccVnName = char.ToUpper(ccVnName.First()) + ccVnName.Substring(1); } string ccEnName = row.Cells["Tên chứng chỉ (tiếng anh)"].Value.ToString(); string ccNumber = row.Cells["Số CC"].Value.ToString(); //string ccCode = "hihi"; string ccCode = new CertificateModel().GetCcCode(ccEnName); GeneratePdf(studentName, studentId, date, ccVnName, ccEnName, ccNumber, folderStoragePath, ccCode, email, e, converter); count++; worker.ReportProgress(count); } } MessageBox.Show("Generate successfull", "Successfull", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); backgroundWorker1.CancelAsync(); } finally { Process.Start(folderStoragePath); } }
public FileResult GenerateAdminReportPdf(string date) { var tempHtmlTemplate = AppDomain.CurrentDomain.BaseDirectory + @"Content\AdminReport.html"; var model = new List <ReportVM>(); string[] startDateSplit = date.Split(','); DateTime?startDate = null; DateTime?endDate = null; if (startDateSplit.Count() >= 2) { startDate = Convert.ToDateTime(startDateSplit[0]); endDate = (Convert.ToDateTime(startDateSplit[1])).AddHours(23).AddMinutes(59); //endDate = endDate.Value.AddHours(23).AddMinutes(59); } model = _adminService.GetReportData(startDate, endDate); string str = RenderPartialToString(this, "AdminReport", model, ViewData, TempData); StringBuilder sb = new StringBuilder(); foreach (var item in model) { string htmlFormat = $"<tr><td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.Request}</td>" + $"<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.EligibleProperties}</td>" + $"<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.InEligibleProperties}</td>" + $"<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.Unknown}</td>"; sb.Append(htmlFormat); } str = str.Replace("#######", sb.ToString()); System.IO.File.WriteAllText(tempHtmlTemplate, str); SelectPdf.HtmlToPdf pdfFile = new SelectPdf.HtmlToPdf(); pdfFile.Options.MarginRight = 5; pdfFile.Options.MarginRight = 5; SelectPdf.PdfDocument document = pdfFile.ConvertUrl(tempHtmlTemplate); //Guid rand = Guid.NewGuid(); //string pdf = Server.MapPath("/Content/test"+ rand+".pdf"); byte[] pd = document.Save(); document.Close(); FileResult fileResult = new FileContentResult(pd, "application/pdf"); fileResult.FileDownloadName = "Report" + DateTime.Now + ".pdf"; return(fileResult); }
public async Task <FileStreamResult> RenderViewAsPdf(string viewName, object model, string fileName) { var htmlString = await RenderViewAsHtml(viewName, model); MemoryStream inMemoryStream = new MemoryStream(); SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf(); SelectPdf.PdfDocument doc = converter.ConvertHtmlString(htmlString); doc.Save(inMemoryStream); doc.Close(); inMemoryStream.Seek(0, SeekOrigin.Begin); var retStream = new FileStreamResult(inMemoryStream, new MediaTypeHeaderValue("application/pdf")); if (!string.IsNullOrEmpty(fileName)) { retStream.FileDownloadName = fileName; } return(retStream); }
private void ConvertToPDF(object state) { var p = state as object[]; var html = p[0].ToString(); var outputFile = p[1].ToString(); var converter = new HtmlToPdf { Options = { PdfPageSize = PdfPageSize.A4, PdfPageOrientation = PdfPageOrientation.Portrait, WebPageWidth = 210, WebPageHeight = 297, CssMediaType = HtmlToPdfCssMediaType.Screen, DrawBackground = true } }; //Generate PDF file var doc = converter.ConvertHtmlString(html); if (File.Exists(outputFile)) { File.Delete(outputFile); } doc.Save(outputFile); doc.Close(); if (ConfigInfo.SaveHtml) { File.WriteAllText(outputFile.Replace(".pdf", ".html"), html, Encoding.UTF8); } BeginInvoke((Action)(() => { barProgress.PerformStep(); lblStatus.Text = $@"Archivo PDF {barProgress.Value}/{barProgress.Maximum}"; })); }
private HtmlToPdf InitConverter() { // define a rendering result object SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf(); //setting up rendering converter.Options.PdfPageOrientation = PdfPageOrientation.Landscape; converter.Options.PdfPageSize = PdfPageSize.A4; converter.Options.DrawBackground = true; converter.Options.EmbedFonts = true; //white outline half of cm converter.Options.MarginLeft = -7; converter.Options.MarginRight = -10; converter.Options.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit; converter.Options.AutoFitWidth = HtmlToPdfPageFitMode.AutoFit; return(converter); }
public static byte[] GetSelectPdf(string htmlString, PdfPageSize pdfPageSize, string Titulo = "", string Autor = "", string Asunto = "", string PalabraClave = "") { byte[] PDFBytes = null; try { SelectPdf.HtmlToPdf htmlToPdf = new SelectPdf.HtmlToPdf(); htmlToPdf.Options.PdfPageSize = pdfPageSize; htmlToPdf.Options.PdfPageOrientation = PdfPageOrientation.Portrait; htmlToPdf.Options.AutoFitWidth = HtmlToPdfPageFitMode.ShrinkOnly; htmlToPdf.Options.WebPageWidth = 1000; htmlToPdf.Options.WebPageHeight = 0; htmlToPdf.Options.MarginLeft = 0; htmlToPdf.Options.MarginRight = 0; htmlToPdf.Options.MarginTop = 0; htmlToPdf.Options.MarginBottom = 0; htmlToPdf.Options.PdfDocumentInformation.Title = Titulo; htmlToPdf.Options.PdfDocumentInformation.Author = Autor; htmlToPdf.Options.PdfDocumentInformation.CreationDate = DateTime.Now; htmlToPdf.Options.PdfDocumentInformation.Subject = Asunto; htmlToPdf.Options.PdfDocumentInformation.Keywords = PalabraClave; //htmlToPdf.Options.JavaScriptEnabled = true; htmlToPdf.Options.RenderingEngine = RenderingEngine.WebKitRestricted; //htmlToPdf.Options.RenderPageOnTimeout = true; //htmlToPdf.Options.MinPageLoadTime = 2; //htmlToPdf.Options.CssMediaType = HtmlToPdfCssMediaType.Screen; SelectPdf.PdfDocument pdf = htmlToPdf.ConvertHtmlString(htmlString); MemoryStream ms = new MemoryStream(); pdf.Save(ms); pdf.Close(); PDFBytes = ms.ToArray(); } catch (Exception ex) { throw ex; } return(PDFBytes); }
public FileResult GenerateProjectReportPdf() { var tempHtmlTemplate = AppDomain.CurrentDomain.BaseDirectory + @"Content\CoverSheet.html"; var model = new List <CoverSheetVM>(); model = _requestService.GetCoverSheetUsers(); string str = RenderPartialToString(this, "ProjectReport", model, ViewData, TempData); StringBuilder sb = new StringBuilder(); foreach (var item in model) { string htmlFormat = string.Format( "<tr><td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{0}</td>" + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{1}</td>" + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{2}</td>" + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{3}</td>" + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{4}</td>" + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{5}</td>" + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{6}</td>" , item.ProjectLogNumber, item.Date, item.ProjectName, item.ApplicantContact.Name, item.ApplicantContact.CountyName, item.LeadLegacy, item.ProjectDescription ); sb.Append(htmlFormat); } str = str.Replace("#######", sb.ToString()); System.IO.File.WriteAllText(tempHtmlTemplate, str); SelectPdf.HtmlToPdf pdfFile = new SelectPdf.HtmlToPdf(); pdfFile.Options.MarginRight = 5; pdfFile.Options.MarginRight = 5; SelectPdf.PdfDocument document = pdfFile.ConvertUrl(tempHtmlTemplate); //Guid rand = Guid.NewGuid(); //string pdf = Server.MapPath("/Content/test"+ rand+".pdf"); byte[] pd = document.Save(); document.Close(); FileResult fileResult = new FileContentResult(pd, "application/pdf"); fileResult.FileDownloadName = "Document.pdf"; return(fileResult); }
//******************************************************************************************** // Save PDF //******************************************************************************************** private void SaveSuppPDF(int id) { try { var tempFilesFolder = Server.MapPath(ConfigurationManager.AppSettings["TempFilesRoot"]); var filename = id + "_Quote.pdf"; var fileloc = tempFilesFolder + "\\"; var fullPath = fileloc + filename; SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf(); string url = Request.Url.Authority + Request.ApplicationPath + "/Quotes/QuoteDetailsSuppPDF/" + id; converter.Options.PdfPageSize = SelectPdf.PdfPageSize.A4; converter.Options.PdfPageOrientation = SelectPdf.PdfPageOrientation.Portrait; SelectPdf.PdfDocument doc = converter.ConvertUrl(url); doc.Save(fullPath); doc.Close(); } catch (Exception ex) { //Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } }
/// <summary> /// Initializes an instance of the HtmlToPdfConverter. /// </summary> public HtmlToPdfConverter() { _internalConverter = new SelectPdf.HtmlToPdf(); }
public string SendLOS(string Token) { var Member = _context.Users.FirstOrDefault(x => x.Token == Token); if (Member != null) { MemoryStream memoryStream = new MemoryStream(); StreamReader streamReader; streamReader = new StreamReader(Directory.GetCurrentDirectory().ToString() + "\\Controllers\\Documents\\Certificate.html"); if (streamReader != null) { string content = streamReader.ReadToEnd(); if (content != null) { content.ToString(); streamReader.Close(); string content1 = content.Replace("Name", Member.Username) .Replace("Type", "Letter Of Dedicated Status") .Replace("Date", "December 2019"); SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf(); converter.Options.PdfPageSize = PdfPageSize.A4; converter.Options.PdfPageOrientation = PdfPageOrientation.Landscape; converter.Options.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit; converter.Options.AutoFitWidth = HtmlToPdfPageFitMode.AutoFit; PdfDocument doc = new PdfDocument(); doc = converter.ConvertHtmlString(content1); if (doc != null) { doc.Save(memoryStream); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); if (bytes != null) { sendMail.SendEmail(Member.Email, "Letter Of Dedicated Status", new Attachment(new MemoryStream(bytes), "LOS.pdf")); doc.Close(); return("Document Sent"); } return("Document Not Sent"); } return("Document Not Sent"); } return("Document Not Sent"); } return("Document Not Sent"); } return("Document Not Sent"); }
private void GeneratePdf(string studentName, string studentId, DateTime date, string ccVnName, string ccEnName, string ccNumber, string folderStoragePath, string ccCode, string email, DoWorkEventArgs ev, SelectPdf.HtmlToPdf converter) { CertificateModel certificateModel = new CertificateModel(); string filePath = null; if (backgroundWorker1.CancellationPending) { ev.Cancel = true; } else { try { string finishedDate = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); string[] parameters = { studentName, ccVnName, ccEnName, ccNumber, finishedDate, Application.ExecutablePath.Remove(Application.ExecutablePath.LastIndexOf("\\")).Replace("\\", "/") }; //string filename = "E:/Funix/Template certificate/certificate template 1.pdf"; filePath = $"{folderStoragePath.Replace("\\", "/")}/{ccNumber}-{ccCode}-{studentName}.pdf"; string html = string.Format(contentHtml, parameters); // define a rendering result object PdfDocument doc = converter.ConvertHtmlString(html); doc.Save(filePath); doc.Close(); //HtmlToImage htmlToImage = new HtmlToImage(); //Image img = htmlToImage.ConvertHtmlString(html); ////TODO: create new file first //FileStream stream = File.Open("D:/Image/test.png", FileMode.Create); //img.Save(stream, ImageFormat.Png); UploadFileToGoogleDrive(studentName, studentId, date, ccEnName, ccNumber, ccCode, email, filePath, ev); } catch (Exception e) { throw e; } } }