public static void CellMerge(string outputFile) { Document document = new Document(); Section sec = document.Sections.AddSection(); sec.AddParagraph("A paragraph before."); Table table = sec.AddTable(); table.Borders.Visible = true; table.AddColumn(); table.AddColumn(); Row row = table.AddRow(); Cell cell = row.Cells[0]; cell.MergeRight = 1; cell.Borders.Visible = true; cell.Borders.Left.Width = 8; cell.Borders.Right.Width = 2; cell.AddParagraph("First Cell"); row = table.AddRow(); cell = row.Cells[1]; cell.AddParagraph("Last Cell within this row"); cell.MergeDown = 1; cell.Borders.Bottom.Width = 15; cell.Borders.Right.Width = 30; cell.Shading.Color = Colors.LightBlue; row = table.AddRow(); sec.AddParagraph("A Paragraph afterwards"); PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = document; renderer.RenderDocument(); renderer.PdfDocument.Save(outputFile); }
/// <summary> /// Tests AddFormattedText. /// </summary> public static void Formatted(string pdfOutputFile) { Document document = new Document(); Section section = document.AddSection(); Paragraph par = section.AddParagraph(); FillFormattedParagraph(par); PdfDocumentRenderer printer = new PdfDocumentRenderer(); printer.Document = document; printer.RenderDocument(); printer.PdfDocument.Save(pdfOutputFile); }
/// <summary> /// Tests texts and blanks. /// </summary> public static void TextAndBlanks(string pdfOutputFile) { Document document = new Document(); Section section = document.AddSection(); Paragraph par = section.AddParagraph("Dies"); for (int idx = 0; idx <= 40; ++idx) { par.AddCharacter(SymbolName.Blank); par.AddText(idx.ToString()); par.AddCharacter(SymbolName.Blank); par.AddText((idx + 1).ToString()); par.AddCharacter(SymbolName.Blank); par.AddText((idx + 2).ToString()); } PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = document; renderer.RenderDocument(); renderer.PdfDocument.Save(pdfOutputFile); }
public static void A1000Paragraphs(string outputFile) { Document doc = new Document(); Section sec = doc.Sections.AddSection(); sec.PageSetup.TopMargin = 0; sec.PageSetup.BottomMargin = 0; for (int idx = 1; idx <= 1000; ++idx) { Paragraph par = sec.AddParagraph(); par.AddText("Paragraph " + idx + ": "); TestParagraphRenderer.FillFormattedParagraph(par); TestParagraphRenderer.GiveBorders(par); } PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(outputFile); }
public static void TwoParagraphs(string outputFile) { Document doc = new Document(); Section sec = doc.Sections.AddSection(); sec.PageSetup.TopMargin = 0; sec.PageSetup.BottomMargin = 0; Paragraph par1 = sec.AddParagraph(); TestParagraphRenderer.FillFormattedParagraph(par1); TestParagraphRenderer.GiveBorders(par1); par1.Format.SpaceAfter = "2cm"; par1.Format.SpaceBefore = "3cm"; Paragraph par2 = sec.AddParagraph(); TestParagraphRenderer.FillFormattedParagraph(par2); TestParagraphRenderer.GiveBorders(par2); par2.Format.SpaceBefore = "3cm"; PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(outputFile); }
/// <summary> /// Print packaging slips to PDF /// </summary> /// <param name="orderCollection">Order collection</param> /// <param name="filePath">File path</param> public static void PrintPackagingSlipsToPdf(OrderCollection orderCollection, string filePath) { if (String.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } Document doc = new Document(); Section section = doc.AddSection(); int ordCount = orderCollection.Count; int ordNum = 0; foreach (var order in orderCollection) { Paragraph p1 = section.AddParagraph(String.Format("{0} #{1}", LocalizationManager.GetLocaleResourceString("PdfPackagingSlip.Order"), order.OrderId)); p1.Format.Font.Bold = true; p1.Format.Font.Color = Colors.Black; p1.Format.Font.Underline = Underline.None; section.AddParagraph(); section.AddParagraph(order.ShippingFullName); section.AddParagraph(order.ShippingAddress1); section.AddParagraph(String.Format("{0}, {1}", order.ShippingCity, order.ShippingZipPostalCode)); section.AddParagraph(); Table productTable = section.AddTable(); productTable.Borders.Visible = true; productTable.AddColumn(Unit.FromCentimeter(4)); productTable.AddColumn(Unit.FromCentimeter(10)); productTable.AddColumn(Unit.FromCentimeter(4)); Row header = productTable.AddRow(); header.Shading.Color = Colors.LightGray; header.Cells[0].Format.Alignment = ParagraphAlignment.Center; header.Cells[0].AddParagraph(LocalizationManager.GetLocaleResourceString("PdfPackagingSlip.QTY")); header.Cells[1].Format.Alignment = ParagraphAlignment.Center; header.Cells[1].AddParagraph(LocalizationManager.GetLocaleResourceString("PdfPackagingSlip.ProductName")); header.Cells[2].Format.Alignment = ParagraphAlignment.Center; header.Cells[2].AddParagraph(LocalizationManager.GetLocaleResourceString("PdfPackagingSlip.SKU")); OrderProductVariantCollection opvc = order.OrderProductVariants; foreach (var orderProductVariant in opvc) { Row row = productTable.AddRow(); row.Cells[0].Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph(orderProductVariant.Quantity.ToString()); string name = String.Format("Not available. ID={0}", orderProductVariant.ProductVariantId); var pv = ProductManager.GetProductVariantById(orderProductVariant.ProductVariantId); if (pv != null) { name = pv.FullProductName; } row.Cells[1].Format.Alignment = ParagraphAlignment.Left; row.Cells[1].AddParagraph(name); Paragraph p2 = row.Cells[1].AddParagraph(HtmlHelper.ConvertHtmlToPlainText(orderProductVariant.AttributeDescription, true)); p2.Format.Font.Italic = true; row.Cells[2].Format.Alignment = ParagraphAlignment.Center; row.Cells[2].AddParagraph(orderProductVariant.ProductVariant.SKU); } ordNum++; if (ordNum < ordCount) { section.AddPageBreak(); } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(filePath); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; foreach (var order in info.Orders) { var orderLabel = section.AddParagraph("Заказ №" + order.Id + " от " + order.OrderDate.ToShortDateString()); orderLabel.Style = "NormalTitle"; orderLabel.Format.SpaceBefore = "1cm"; orderLabel.Format.SpaceAfter = "0,25cm"; var furnitureModelLabel = section.AddParagraph("Мебель:"); furnitureModelLabel.Style = "NormalTitle"; var serviceTable = document.LastSection.AddTable(); List <string> headerWidths = new List <string> { "1cm", "4cm", "3cm", "2,5cm", "3cm", "2,5cm" }; foreach (var elem in headerWidths) { serviceTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "№", "Тип", "Модель", "Цена", "Количество", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); int i = 1; foreach (var position in order.Positions) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { i.ToString(), position.TypeName, position.ModelName, position.Price.ToString(), position.Count.ToString(), (position.Price * position.Count).ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "", "", "Итого:", order.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); if (order.Status == PaymentStatus.Оформлен) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "", "", "К оплате:", order.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } else { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "", "", "К оплате:", order.LeftSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } if (info.Payments[order.Id].Count == 0) { continue; } var paymentsLabel = section.AddParagraph("Платежи:"); paymentsLabel.Style = "NormalTitle"; var paymentTable = document.LastSection.AddTable(); headerWidths = new List <string> { "1cm", "7,5cm", "7,5cm" }; foreach (var elem in headerWidths) { paymentTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { "№", "Дата", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); i = 1; foreach (var payment in info.Payments[order.Id]) { CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { i.ToString(), payment.PaymentDate.ToString(), payment.PaymentAmount.ToString(), }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
public PdfUtility() { _documentSection = _document.AddSection(); _document = new Document(); _renderer = new PdfDocumentRenderer(); }
public static void CreateTeamsPDF(List <TeamSet> teams, Client.DataAccess c, String pathToPDF) { Document doc = new Document(); doc.Info.Author = "*****@*****.**"; doc.Info.Comment = "Generated from ANRL Client on " + DateTime.Now.ToString(); doc.Info.Keywords = "ANRL Crewlist"; doc.Info.Subject = "Crewlist"; doc.Info.Title = "Crewlist"; doc.UseCmykColor = true; doc.DefaultPageSetup.PageFormat = PageFormat.A4; doc.DefaultPageSetup.Orientation = Orientation.Landscape; doc.DefaultPageSetup.BottomMargin = Unit.FromCentimeter(1); doc.DefaultPageSetup.TopMargin = Unit.FromCentimeter(1); doc.DefaultPageSetup.LeftMargin = Unit.FromCentimeter(1.5); doc.DefaultPageSetup.RightMargin = Unit.FromCentimeter(1); Section sec = doc.AddSection(); AddCompetitionAndLogo(c, sec); sec.AddParagraph(""); sec.AddParagraph("Participants list"); sec.AddParagraph(""); Table table = sec.AddTable(); table.Borders.Visible = true; //table.AddColumn(Unit.FromCentimeter(0.7)); table.AddColumn(Unit.FromCentimeter(2.5)); table.AddColumn(); table.AddColumn(Unit.FromCentimeter(4)); table.AddColumn(Unit.FromCentimeter(4)); table.AddColumn(Unit.FromCentimeter(4)); table.AddColumn(Unit.FromCentimeter(4)); table.AddColumn(); Row row = table.AddRow(); row.Shading.Color = Colors.Gray; //row.Cells[0].AddParagraph("ID"); row.Cells[0].AddParagraph("CNumber"); row.Cells[1].AddParagraph("Nationality"); row.Cells[2].AddParagraph("Pilot Lastname"); row.Cells[3].AddParagraph("Pilot Firstname"); row.Cells[4].AddParagraph("Navigator Lastname"); row.Cells[5].AddParagraph("Navigator Firstname"); row.Cells[6].AddParagraph("AC"); foreach (TeamSet t in teams) { Row r = table.AddRow(); //r.Cells[0].AddParagraph(t.ID.ToString()); r.Cells[0].AddParagraph(t.CNumber); r.Cells[1].AddParagraph(t.Nationality); SubscriberSet pilot = t.Pilot; r.Cells[2].AddParagraph(pilot.LastName); r.Cells[3].AddParagraph(pilot.FirstName); if (t.Navigator != null) { SubscriberSet navigator = t.Navigator; r.Cells[4].AddParagraph(navigator.LastName); r.Cells[5].AddParagraph(navigator.FirstName); } r.Cells[6].AddParagraph(t.AC); } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(pathToPDF); Process.Start(pathToPDF); }
public async Task ExportStaffPasswordToPDF(string name, string username, string mail, string copycode, string networkPassword = null, string smartschoolPassword = null) { await Task.Run(() => { var document = createDocument(); var section = document.AddSection(); section.AddParagraph("Account voor " + name, "Heading1"); section.AddParagraph("Login Gegevens", "Heading2"); section.AddParagraph("Login : "******"PasswordStyle"); section.AddParagraph("Copy Code : " + copycode, "PasswordStyle"); if (networkPassword != null) { section.AddParagraph("Wachtwoord: " + networkPassword, "PasswordStyle"); section.AddParagraph("Met deze gegevens kan je inloggen op de pc's op school. Je kan er ook mee " + "inloggen op het Smifi-P wifi netwerk.", "Normal"); section.AddParagraph("Office365", "Heading2"); section.AddParagraph("Je beschikt ook over een Office365 account waarmee je kan inloggen op https://www.office.com/. Je kan dit e-mail adres gebruiken, maar de " + "communicatie met de school en je leerlingen verloopt steeds via smartschool. Je kan wel alle Office365 programma's zoals Word en " + "Powerpoint online gebruiken of installeren op een computer naar keuze.", "Normal"); section.AddParagraph("Login : "******"PasswordStyle"); section.AddParagraph("Wachtwoord: " + networkPassword, "PasswordStyle"); } if (smartschoolPassword != null) { section.AddParagraph("Smartschool", "Heading2"); section.AddParagraph("Je gebruikt de website https://sanctamaria-aarschot.smartschool.be", "Normal"); section.AddParagraph("Je kan inloggen bij smartschool met deze login, en het volgende wachtwoord:", "Normal"); section.AddParagraph(smartschoolPassword, "PasswordStyle"); section.AddParagraph("Wanneer je inlogt, zal smartschool je verplichten om een nieuw wachtwoord te kiezen.", "Normal"); } section.AddParagraph("Privacy", "Heading2"); section.AddParagraph("Je account is strikt persoonlijk. Indien je je account doorgeeft aan anderen, dan ben jij " + "verantwoordelijk voor hun acties op het netwerk. Laat dit blad dus niet rondslingeren maar leer je login " + "en wachtwoord vanbuiten. Zou je je wachtwoord vergeten, dan kan je een nieuw wachtwoord krijgen op Secretariaat 1.", "Normal"); section.AddParagraph("Geef nooit (NOOIT!) je wachtwoord door, ook niet aan collegas."); var pdfRenderer = new PdfDocumentRenderer(); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); string fileName = name + ".pdf"; try { pdfRenderer.PdfDocument.Save(fileName); List.Clear(); } catch (Exception) { MainWindow.Instance.Log.AddError(AccountApi.Origin.Other, "Unable to save to file: " + fileName); } Process.Start(fileName); }).ConfigureAwait(false); }
public static void VerticalAlign(string outputFile) { Document document = new Document(); Section sec = document.Sections.AddSection(); sec.AddParagraph("A paragraph before."); Table table = sec.AddTable(); table.Borders.Visible = true; table.AddColumn(); table.AddColumn(); Row row = table.AddRow(); row.HeightRule = RowHeightRule.Exactly; row.Height = 70; row.VerticalAlignment = VerticalAlignment.Center; row[0].AddParagraph("First Cell"); row[1].AddParagraph("Second Cell"); sec.AddParagraph("A Paragraph afterwards."); PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = document; renderer.RenderDocument(); renderer.PdfDocument.Save(outputFile); }
private void ProcessVerificationResponse(string response, string paymentDetails) { // postoji i polje "payment_date", (svi podaci o uplatiocu(ime, prezime, adresa)) Dictionary <string, string> details = organizeDetails(paymentDetails); if (response.Equals("VERIFIED")) { if (!details.ContainsKey("receiver_email") || !details.ContainsKey("payment_status") || !details.ContainsKey("item_name") || !details.ContainsKey("item_number")) { return; // ukoliko nam nije dostupan neki od osnovnih podataka } if (!details["receiver_email"].Equals(ACCOUNT_EMAIL)) { return; // transakcija nije namenjena meni } if (!details["payment_status"].Equals("Completed")) { return; // nije prosla transakcija } if (!details["item_name"].Equals(POLICY_NAME)) { return; // nije placeno osiguranje vec nesto drugo } string policyIdStr = details["item_number"]; int policyId = Int32.Parse(policyIdStr); string currency = "", ammount = ""; if (details.ContainsKey("mc_currency")) { currency = details["mc_currency"]; } if (details.ContainsKey("mc_gross")) { ammount = details["mc_gross"]; } // upisati u bazu za odgovarajucu polisu da je placanje izvrseno // upisati u bazu za odgovarajucu polisu id transakcije // nadji datu polisu u bazi Realizacija_osiguranja ro = db.Realizacija_osiguranja.Where(r => r.Id_Realizacija_osiguranja == policyId).FirstOrDefault();//.Include(s => s.Stavka_u_realizaciji) if (ro != null) { // proveriti da li se valuta i placeni iznos poklapaju sa ocekivanim //if (ro.Ukupna_vrednost_Realizacija_osiguranja.Equals(Decimal.Parse(ammount))) Zakomentarisano zbog konverzije evro-dinar, nikada vise nece biti isto :D //{ if (!ro.Potvrdjena_Realizacija_osiguranja) { ro.Potvrdjena_Realizacija_osiguranja = true; ro.Broj_transakcije_Realizacija_osiguranja = details["txn_id"]; db.SaveChanges(); try { var sur = db2.Stavka_u_realizaciji.Where(s => s.Id_Realizacija_osiguranja == ro.Id_Realizacija_osiguranja).Where(s => s.Nosilac_Stavka_u_realiziciji == true).Include(s => s.Osoba).FirstOrDefault(); var osoba = db2.Osoba.Where(o => o.Id_Osigurani_entitet == sur.Id_Osigurana_osoba).FirstOrDefault(); if (osoba != null) { var mail_carr = osoba.E_mail_Osoba; //Kreiranje pdf-a //slanje mail-a PDFCreator creator = new PDFCreator(); var fullPath = System.Web.HttpContext.Current.Server.MapPath("../fonts/logo.png"); Document doc = creator.createDocument(ro, fullPath); PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true); pdfRenderer.Document = doc; pdfRenderer.RenderDocument(); MemoryStream ms = new MemoryStream(); pdfRenderer.Save(ms, false); ms.Position = 0; NetworkCredential basicCredential = new NetworkCredential("*****@*****.**", "hasansakic"); MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); mail.To.Add(mail_carr); mail.Subject = "Polisa osiguranja - Holiday Guard"; mail.Body = "Pozdrav, \n šaljemo vam vašu polisu jer ste naznačeni kao nosilac. Za sve informacije možete se obratiti na telefon 021/ 4540 021. \n Svako dobro, \n Vaš Holiday Guard!"; mail.Attachments.Add(new Attachment(ms, "polisa.pdf", "application/pdf")); SmtpServer.Port = 587; SmtpServer.Credentials = basicCredential; SmtpServer.EnableSsl = true; SmtpServer.Send(mail); ms.Close(); } } catch (Exception e) { Console.Write(e); // Log... Console.Write(e.InnerException); } } //} } } else { //upisati u redovan log //upisati u log potencijalnih opasnosti string email = "", status = ""; if (details.ContainsKey("payer_email")) { email = details["payer_email"]; } if (details.ContainsKey("payer_status")) { status = details["payer_status"]; // da li ima verifikovan nalog na paypal-u } } }
public static void CreateInvoice(PO.Order order, bool sendEmail = true) { Document document = new Document(); //document.Info.Title = "invoice"; //document.Info.Subject = "Demonstrates how to create an invoice."; //document.Info.Author = "Stefan Lange"; // Get the predefined style Normal. Style style = document.Styles["Normal"]; // Because all styles are derived from Normal, the next line changes the // font of the whole document. Or, more exactly, it changes the font of // all styles and paragraphs that do not redefine the font. style.Font.Name = "Verdana"; style = document.Styles[StyleNames.Header]; style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right); style = document.Styles[StyleNames.Footer]; style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center); // Create a new style called Table based on style Normal style = document.Styles.AddStyle("Table", "Normal"); style.Font.Name = "Verdana"; style.Font.Name = "Times New Roman"; style.Font.Size = 9; // Create a new style called Reference based on style Normal style = document.Styles.AddStyle("Reference", "Normal"); style.ParagraphFormat.SpaceBefore = "5mm"; style.ParagraphFormat.SpaceAfter = "5mm"; style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right); // Each MigraDoc document needs at least one section. Section section = document.AddSection(); // Create footer Paragraph paragraph = section.Footers.Primary.AddParagraph(); paragraph.AddText("Household Goods World Ltd · 9 Egerton Road · London · N16 6UE · England · Company No. 05713446"); paragraph.Format.Font.Size = 9; paragraph.Format.Alignment = ParagraphAlignment.Center; // Create the text frame for the address TextFrame addressFrame = section.AddTextFrame(); addressFrame.Height = "3.0cm"; addressFrame.Width = "7.0cm"; addressFrame.Left = ShapePosition.Left; addressFrame.RelativeHorizontal = RelativeHorizontal.Margin; addressFrame.Top = "5.5cm"; addressFrame.RelativeVertical = RelativeVertical.Page; // Create the text frame for the address TextFrame companyFrame = section.AddTextFrame(); companyFrame.Height = "3.0cm"; companyFrame.Width = "7.0cm"; companyFrame.Left = ShapePosition.Outside; companyFrame.RelativeHorizontal = RelativeHorizontal.Margin; companyFrame.Top = "4.5cm"; companyFrame.RelativeVertical = RelativeVertical.Page; // Put sender in address frame //paragraph = addressFrame.AddParagraph("Household Goods World ltd · 9 Egerton Road · N16 6UE London"); paragraph.Format.Font.Name = "Times New Roman"; paragraph.Format.Font.Size = 7; paragraph.Format.SpaceAfter = 3; // Add the print date field paragraph = section.AddParagraph(); paragraph.Format.SpaceBefore = "8cm"; paragraph.Style = "Reference"; paragraph.AddFormattedText("INVOICE #" + order.OrderID, TextFormat.Bold); paragraph.AddTab(); //paragraph.AddText("London, "); //paragraph.AddDateField("dd.MM.yyyy"); paragraph.AddText(order.OrderTime.ToShortDateString()); // Create the item table Table table = section.AddTable(); table.Style = "Table"; table.Borders.Color = Colors.Black; table.Borders.Width = 0.25; table.Borders.Left.Width = 0.5; table.Borders.Right.Width = 0.5; table.Rows.LeftIndent = 0; // Before you can add a row, you must define the columns Column column = table.AddColumn("1cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("2.5cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("2.5cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("9cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("2cm"); column.Format.Alignment = ParagraphAlignment.Left; // Create the header of the table Row row = table.AddRow(); row.HeadingFormat = true; row.Format.Alignment = ParagraphAlignment.Center; row.Format.Font.Bold = true; row.Shading.Color = Colors.LightGray; row.Cells[0].AddParagraph("Item"); row.Cells[0].Format.Font.Bold = false; row.Cells[0].Format.Alignment = ParagraphAlignment.Left; row.Cells[1].AddParagraph("Brand"); row.Cells[1].Format.Alignment = ParagraphAlignment.Left; row.Cells[2].AddParagraph("Model Number"); row.Cells[2].Format.Alignment = ParagraphAlignment.Left; row.Cells[3].AddParagraph("Description"); row.Cells[3].Format.Alignment = ParagraphAlignment.Left; row.Cells[4].AddParagraph("Price"); row.Cells[4].Format.Alignment = ParagraphAlignment.Left; table.SetEdge(0, 0, 5, 1, Edge.Box, BorderStyle.Single, 0.75, Color.Empty); // Fill address in address text frame Paragraph paragraph1 = addressFrame.AddParagraph(); paragraph1.AddText(order.Customer.Name); paragraph1.AddLineBreak(); if (order.Customer.Company != "") { paragraph1.AddText(order.Customer.Company); paragraph1.AddLineBreak(); } paragraph1.AddText(order.Customer.Address); paragraph1.AddLineBreak(); paragraph1.AddText(order.Customer.City); paragraph1.AddLineBreak(); paragraph1.AddText(order.Customer.PostCode); // Fill address in company text frame Paragraph paragraph2 = companyFrame.AddParagraph(); paragraph2.Format.Alignment = ParagraphAlignment.Right; paragraph2.Format.Font.Size = 12; paragraph2.AddFormattedText("Household Goods World Ltd", TextFormat.Bold); paragraph2.AddLineBreak(); paragraph2.AddText("9 Egerton Road"); paragraph2.AddLineBreak(); paragraph2.AddText("London"); paragraph2.AddLineBreak(); paragraph2.AddText("N16 6UE"); // Iterate the invoice items var iter = order.Items.GetEnumerator(); while (iter.MoveNext()) { if (iter.Current is PO.Item) { var item = iter.Current as PO.Item; double price = item.Price; // Each item fills two rows Row row1 = table.AddRow(); row1.TopPadding = 1.5; row1.Cells[0].VerticalAlignment = VerticalAlignment.Center; row1.Cells[1].Format.Alignment = ParagraphAlignment.Left; row1.Cells[0].AddParagraph(item.ItemID); row1.Cells[1].AddParagraph(item.Brand); row1.Cells[2].AddParagraph(item.ModelNumber); row1.Cells[3].AddParagraph(item.Description); row1.Cells[4].AddParagraph(item.Price.ToString("C", new CultureInfo("en-GB", false).NumberFormat)); } else { var item = iter.Current as PO.Payment; Row row1 = table.AddRow(); row1.TopPadding = 1.5; row1.Cells[0].VerticalAlignment = VerticalAlignment.Center; row1.Cells[1].Format.Alignment = ParagraphAlignment.Left; row1.Cells[1].AddParagraph("Paid"); row1.Cells[4].AddParagraph(item.Price.ToString("C", new CultureInfo("en-GB", false).NumberFormat)); //row1.Cells[4].AddParagraph("-" + order.Items.Sum(it => it.Price).ToString("C", new CultureInfo("en-GB", false).NumberFormat)); table.SetEdge(0, table.Rows.Count - 2, 5, 2, Edge.Box, BorderStyle.Single, 0.75); } table.SetEdge(0, table.Rows.Count - 2, 5, 2, Edge.Box, BorderStyle.Single, 0.75); } // Add an invisible row as a space line to the table Row row2 = table.AddRow(); row.Borders.Visible = false; // Add the total price row row2 = table.AddRow(); row2.Cells[0].Borders.Visible = false; row2.Cells[0].AddParagraph("Total Price"); row2.Cells[0].Format.Font.Bold = true; row2.Cells[0].Format.Alignment = ParagraphAlignment.Right; row2.Cells[0].MergeRight = 3; row2.Cells[4].AddParagraph(order.TotalPrice.ToString("C", new CultureInfo("en-GB", false).NumberFormat)); // Add the additional fee row Row row3 = table.AddRow(); row3.Cells[0].Borders.Visible = false; row3.Cells[0].AddParagraph("Shipping and Handling"); row3.Cells[4].AddParagraph(0.ToString("C", new CultureInfo("en-GB", false).NumberFormat)); row3.Cells[0].Format.Font.Bold = true; row3.Cells[0].Format.Alignment = ParagraphAlignment.Right; row3.Cells[0].MergeRight = 3; // Add the total due row Row row4 = table.AddRow(); row4.Cells[0].AddParagraph("Total Due"); row4.Cells[0].Borders.Visible = false; row4.Cells[0].Format.Font.Bold = true; row4.Cells[0].Format.Alignment = ParagraphAlignment.Right; row4.Cells[0].MergeRight = 3; row4.Cells[4].AddParagraph(order.TotalPrice.ToString("C", new CultureInfo("en-GB", false).NumberFormat)); // Set the borders of the specified cell range table.SetEdge(4, table.Rows.Count - 3, 1, 3, Edge.Box, BorderStyle.Single, 0.75); // Add the notes paragraph paragraph = document.LastSection.AddParagraph(); paragraph.Format.SpaceBefore = "1cm"; paragraph.Format.Borders.Width = 0.75; paragraph.Format.Borders.Distance = 3; //paragraph.Format.Borders.Color = TableBorder; //paragraph.Format.Shading.Color = TableGray; //item = SelectItem("/invoice"); paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.AddFormattedText("Thank you for your business - we appreciate it very much.", TextFormat.Italic); // Add the notes paragraph paragraph = document.LastSection.AddParagraph(); paragraph.Format.SpaceBefore = "1cm"; paragraph.Format.Borders.Width = 0.75; paragraph.Format.Borders.Distance = 3; paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.AddText(@"Bank details; HSBC Household Goods World Limited Sort Code: 40-06-25 Account Number: 21469371"); PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); string fileName = "INV_" + order.OrderID + ".pdf"; if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\ElectricalWorld\Invoice\")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\ElectricalWorld\Invoice\"); } pdfRenderer.PdfDocument.Save(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\ElectricalWorld\Invoice\" + fileName); Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\ElectricalWorld\Invoice\" + fileName); //if (order.Customer.Email != "" && sendEmail) // EmailInvoice(order/*, Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\ElectricalWorld\Invoice\" + fileName*/); }
public IActionResult OnGet(string pdf) { //get the session first! UserName = HttpContext.Session.GetString(SessionKeyName1); FirstName = HttpContext.Session.GetString(SessionKeyName2); SessionID = HttpContext.Session.GetString(SessionKeyName3); DatabaseConnect dbstring = new DatabaseConnect(); //creating an object from the class string DbConnection = dbstring.DatabaseString(); //calling the method from the class Console.WriteLine(DbConnection); SqlConnection conn = new SqlConnection(DbConnection); conn.Open(); using (SqlCommand command = new SqlCommand()) { command.Connection = conn; command.CommandText = @"SELECT * FROM UserTable"; var reader = command.ExecuteReader(); User = new List <User>(); while (reader.Read()) { User Row = new User(); //each record found from the table Row.Id = reader.GetInt32(0); Row.FirstName = reader.GetString(1); Row.UserName = reader.GetString(2); Row.Role = reader.GetString(4); // We dont get the password. The role field is in the 5th position User.Add(Row); } } //PDF code here! if (pdf == "1") { //Create an object for pdf document Document doc = new Document(); Section sec = doc.AddSection(); Paragraph para = sec.AddParagraph(); para.Format.Font.Name = "Arial"; para.Format.Font.Size = 14; para.Format.Font.Color = Color.FromCmyk(0, 0, 0, 100); //black colour para.AddFormattedText("List of Users", TextFormat.Bold); para.Format.SpaceAfter = "1.0cm"; para.AddFormattedText(); //Table Table tab = new Table(); tab.Borders.Width = 0.75; tab.TopPadding = 5; tab.BottomPadding = 5; //Column Column col = tab.AddColumn(Unit.FromCentimeter(1.5)); col.Format.Alignment = ParagraphAlignment.Justify; tab.AddColumn(Unit.FromCentimeter(3)); tab.AddColumn(Unit.FromCentimeter(3)); tab.AddColumn(Unit.FromCentimeter(2)); //Row Row row = tab.AddRow(); row.Shading.Color = Colors.Coral;//select your preference colour! //Cell for header Cell cell = new Cell(); cell = row.Cells[0]; cell.AddParagraph("No."); cell = row.Cells[1]; cell.AddParagraph("First Name"); cell = row.Cells[2]; cell.AddParagraph("User Name"); cell = row.Cells[3]; cell.AddParagraph("Role"); //Add data to table for (int i = 0; i < User.Count; i++) { row = tab.AddRow(); cell = row.Cells[0]; cell.AddParagraph(Convert.ToString(i + 1)); cell = row.Cells[1]; cell.AddParagraph(User[i].FirstName); cell = row.Cells[2]; cell.AddParagraph(User[i].UserName); cell = row.Cells[3]; cell.AddParagraph(User[i].Role); } tab.SetEdge(0, 0, 4, (User.Count + 1), Edge.Box, BorderStyle.Single, 1.5, Colors.Black); sec.Add(tab); //Rendering PdfDocumentRenderer pdfRen = new PdfDocumentRenderer(); pdfRen.Document = doc; pdfRen.RenderDocument(); //Create a memory stream MemoryStream stream = new MemoryStream(); pdfRen.PdfDocument.Save(stream); //saving the file into the stream Response.Headers.Add("content-disposition", new[] { "inline; filename = ListofUser.pdf" }); return(File(stream, "application/pdf")); } return(Page()); }
public MemoryStream CreateOrderStream(Guid orderId) { MigraDoc.DocumentObjectModel.Document document = new MigraDoc.DocumentObjectModel.Document(); document.Info.Title = "Order Request"; document.Info.Subject = "COUNTRY OFFICE, UGANDA"; document.Info.Author = "DRC"; this.section = document.AddSection(); Image image = section.Headers.Primary.AddImage(HttpContext.Current.Server.MapPath("/Content/reports/logos-90.png")); image.LockAspectRatio = true; image.RelativeVertical = RelativeVertical.Line; image.RelativeHorizontal = RelativeHorizontal.Margin; image.Top = ShapePosition.Top; image.Left = "13cm"; image.WrapFormat.Style = WrapStyle.Through; TextFrame heading = this.section.AddTextFrame(); Paragraph tmpHeadParagraph = heading.AddParagraph("ORDER REQUEST"); tmpHeadParagraph.Format.Alignment = ParagraphAlignment.Center; heading.Top = ShapePosition.Top; heading.Width = "12.0cm"; heading.Height = "0.8cm"; TextFrame countryOfficeAddressFrame; countryOfficeAddressFrame = section.AddTextFrame(); countryOfficeAddressFrame.Height = "3.0cm"; countryOfficeAddressFrame.Width = "3.0cm"; countryOfficeAddressFrame.Left = ShapePosition.Right; countryOfficeAddressFrame.RelativeHorizontal = RelativeHorizontal.Margin; countryOfficeAddressFrame.Top = "3.7cm"; countryOfficeAddressFrame.RelativeVertical = RelativeVertical.Page; Paragraph paragraph; paragraph = countryOfficeAddressFrame.AddParagraph("DANISH REFUGEE COUNCIL"); paragraph.Format.Font.Name = "Calibri"; paragraph.Format.Font.Size = 7; paragraph.Format.SpaceAfter = 3; paragraph.AddLineBreak(); paragraph.AddText("Borgergade 10"); paragraph.AddLineBreak(); paragraph.AddText("DK-1300 Copenhagen"); paragraph.AddLineBreak(); paragraph.AddText("Denmark"); paragraph.AddLineBreak(); paragraph.AddLineBreak(); paragraph.AddFormattedText("COUNTRY OFFICE, UGANDA", TextFormat.Bold); paragraph.AddLineBreak(); paragraph.AddText("4688 Kalungi Road"); paragraph.AddLineBreak(); paragraph.AddText("Muyenga, Kampala"); paragraph = countryOfficeAddressFrame.AddParagraph("www.drc.dk"); paragraph.Format.Font.Name = "Calibri"; paragraph.Format.Font.Size = 7; paragraph.Format.Font.Color = new Color(58, 162, 213); paragraph.Format.Font.Underline = Underline.Single; paragraph.AddLineBreak(); paragraph.AddText("WWW.danishdemininggroup.dk"); List <double> sizes = new List <double>(); sizes.AddRange(new double[] { 4.0, 4.0, 4.0 }); DataTable t = this.GetTable(orderId); PrintTable printTable = new PrintTable(t, sizes); this.summaryTable = section.AddTable(); printTable.GenerateTable(this.summaryTable); heading = this.section.AddTextFrame(); heading.Top = "0.9cm"; heading.Width = Unit.FromCentimeter(14.0); tmpHeadParagraph = heading.AddParagraph("Specification/Description, Unit, Quantities, Estimated Prices & PN/BL."); tmpHeadParagraph.Format.Alignment = ParagraphAlignment.Center; heading.Height = Unit.FromCentimeter(2.0); sizes = new List <double>(); sizes.AddRange(new double[] { 1.0, 3.5, 1.0, 1.0, 2.5, 3.5, 1.0, 2.0, 2.5 }); t = this.GetDetailsTable(orderId); TableOptions options = new TableOptions(); options.FontSizeCm = 9.0; printTable = new PrintTable(t, sizes, options); Table dTable = section.AddTable(); printTable.GenerateTable(dTable); section.AddParagraph(Environment.NewLine); sizes = new List <double>(); sizes.AddRange(new double[] { 4.5, 4.5, 4.5, 4.5 }); t = this.GetTableApproval(orderId); options = new TableOptions(); options.FontSizeCm = 9.0; printTable = new PrintTable(t, sizes, options); dTable = section.AddTable(); printTable.GenerateTable(dTable); PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true); // Set the MigraDoc document pdfRenderer.Document = document; // Create the PDF document pdfRenderer.RenderDocument(); MemoryStream stream = new MemoryStream(); pdfRenderer.Save(stream, false); return(stream); }
/////////////////////// /// private void CreatePDF() { #region FillDataTab DataTable dataTable = new DataTable(); dataTable.Columns.Add("Parametr"); dataTable.Columns.Add("Value"); dataTable.Columns.Add("Unit"); DataRow dr1 = dataTable.NewRow(); dr1[0] = ""; dr1[1] = Department; dr1[2] = ""; dataTable.Rows.Add(dr1); DataRow dr2 = dataTable.NewRow(); dr2[0] = ""; dr2[1] = Fio; dr2[2] = ""; dataTable.Rows.Add(dr2); DataRow dr3 = dataTable.NewRow(); dr3[0] = ""; dr3[1] = TireType; dr2[2] = ""; dataTable.Rows.Add(dr3); DataRow dr4 = dataTable.NewRow(); dr4[0] = ""; dr4[1] = TireNomber; dr4[2] = ""; dataTable.Rows.Add(dr4); DataRow dr5 = dataTable.NewRow(); dr5[0] = ""; dr5[1] = TireSize; dr5[2] = ""; dataTable.Rows.Add(dr5); DataRow dr6 = dataTable.NewRow(); dr6[0] = ""; dr6[1] = TestTypeProp.Name; dr6[2] = ""; dataTable.Rows.Add(dr6); DataRow dr7 = dataTable.NewRow(); dr7[0] = "Температура"; dr7[1] = temperature; dr7[2] = "°C"; dataTable.Rows.Add(dr7); DataRow dr8 = dataTable.NewRow(); dr8[0] = ""; dr8[1] = "Формула"; dr8[2] = ""; dataTable.Rows.Add(dr8); DataRow dr9 = dataTable.NewRow(); dr9[0] = ""; dr9[1] = TestTypeProp.ForceName; dr9[2] = ""; dataTable.Rows.Add(dr9); DataRow dr10 = dataTable.NewRow(); dr10[0] = ""; dr10[1] = TestTypeProp.HalfForceName; dr10[2] = ""; dataTable.Rows.Add(dr10); DataRow dr11 = dataTable.NewRow(); dr11[0] = ""; dr11[1] = TestTypeProp.WayName; dr11[2] = ""; dataTable.Rows.Add(dr11); DataRow dr12 = dataTable.NewRow(); dr12[0] = ""; dr12[1] = TestTypeProp.HalfWayName; dr12[2] = ""; dataTable.Rows.Add(dr12); DataRow dr13 = dataTable.NewRow(); dr13[0] = ""; dr13[1] = TestTypeProp.KoefName; dr13[2] = ""; dataTable.Rows.Add(dr13); DataRow dr14 = dataTable.NewRow(); dr14[0] = ""; dr14[1] = TestTypeProp.Formula; dr14[2] = ""; dataTable.Rows.Add(dr14); DataRow dr15 = dataTable.NewRow(); dr15[0] = ""; dr15[1] = TestTypeProp.ForceValue; dr15[2] = ""; dataTable.Rows.Add(dr15); DataRow dr16 = dataTable.NewRow(); dr16[0] = ""; dr16[1] = TestTypeProp.HalfForceValue; dr16[2] = ""; dataTable.Rows.Add(dr16); DataRow dr17 = dataTable.NewRow(); dr17[0] = ""; dr17[1] = TestTypeProp.WayValue; dr17[2] = ""; dataTable.Rows.Add(dr17); DataRow dr18 = dataTable.NewRow(); dr18[0] = ""; dr18[1] = TestTypeProp.HalfWayValue; dr18[2] = ""; dataTable.Rows.Add(dr18); DataRow dr19 = dataTable.NewRow(); dr19[0] = ""; dr19[1] = TestTypeProp.KoefValue; dr19[2] = ""; dataTable.Rows.Add(dr19); DataRow dr20 = dataTable.NewRow(); dr20[0] = ""; dr20[1] = Radius; dr20[2] = ""; dataTable.Rows.Add(dr20); DataRow dr21 = dataTable.NewRow(); dr21[0] = ""; dr21[1] = RealGetForceMax; dr21[2] = ""; dataTable.Rows.Add(dr21); DataRow dr22 = dataTable.NewRow(); dr22[0] = ""; dr22[1] = Pressure; dr22[2] = ""; dataTable.Rows.Add(dr22); DataRow dr23 = dataTable.NewRow(); dr23[0] = ""; dr23[1] = UpperLoad; dr23[2] = ""; dataTable.Rows.Add(dr23); #endregion switch (_testType.Id) { case 1: _testType.HalfForceValue = HalfForce_1; _testType.HalfWayValue = HalfPos_1; _testType.ForceValue = ST_Force_1; _testType.WayValue = ST_Way_1; _testType.KoefValue = Koef_1; break; case 2: _testType.HalfForceValue = HalfForce_2; _testType.HalfWayValue = HalfPos_2; _testType.ForceValue = ST_Force_2; _testType.WayValue = ST_Way_2; _testType.KoefValue = Koef_2; break; case 3: _testType.HalfForceValue = HalfForce_3; _testType.HalfWayValue = HalfPos_3; _testType.ForceValue = ST_Force_3; _testType.WayValue = ST_Way_3; _testType.KoefValue = Koef_3; break; } //try //{ PDF_Tab pDF_Tab = new PDF_Tab(/*"/Projects/PDF/Invoice/invoice.xml",*/ dataTable, _testType); var document = pDF_Tab.CreateDocument(); document.UseCmykColor = true; var pdfRenderer = new PdfDocumentRenderer(true); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); var filename = "Invoice.pdf"; pdfRenderer.Save(filename); Process.Start(filename); var filenameRTF = "Invoice.rtf"; RtfDocumentRenderer rtf = new RtfDocumentRenderer(); rtf.Render(document, filenameRTF, null); Process.Start(filenameRTF); //} //catch (Exception ex) { } }
private void ResetDocument() { this.renderer = new PdfDocumentRenderer(); this.document = new Document(); this.section = this.document.AddSection(); }
/// <summary> /// Tests tab stops. /// </summary> public static void Tabs(string pdfOutputFile) { Document document = new Document(); Section section = document.AddSection(); section.PageSetup.LeftMargin = 0; section.PageSetup.RightMargin = 0; Paragraph par = section.AddParagraph(); par.Format.TabStops.AddTabStop("20cm", TabAlignment.Right); par.AddText(" text before tab bla bla bla. text before tab bla bla bla. text before tab bla bla bla. text before tab bla bla bla."); //par.AddTab(); par.AddText(" ............ after tab bla bla bla."); PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = document; renderer.RenderDocument(); renderer.PdfDocument.Save(pdfOutputFile); }
public PdfService() { this.renderer = new PdfDocumentRenderer(); this.document = new Document(); this.section = this.document.AddSection(); }
private void btn_printCasterHelpSheet_Click(object sender, EventArgs e) { Document document = new Document(); var section = document.AddSection(); section.PageSetup.Orientation = Orientation.Landscape; section.AddParagraph(seasonData.slug + " / " + divData.slug + " / " + teamLeft + " VS. " + teamRight + " " + matchData.tbp); Table table = section.AddTable(); table.Borders.Width = 0.25; table.Rows.LeftIndent = 0; Column column = table.AddColumn("2.5cm"); Column column2 = table.AddColumn("3.5cm"); Column column3 = table.AddColumn("1.5cm"); Column column4 = table.AddColumn("4cm"); Column column5 = table.AddColumn("2.5cm"); Column column6 = table.AddColumn("3.5cm"); Column column7 = table.AddColumn("1.5cm"); Column column8 = table.AddColumn("4cm"); column.Format.Alignment = ParagraphAlignment.Left; column2.Format.Alignment = ParagraphAlignment.Center; column3.Format.Alignment = ParagraphAlignment.Center; column4.Format.Alignment = ParagraphAlignment.Left; column5.Format.Alignment = ParagraphAlignment.Center; column6.Format.Alignment = ParagraphAlignment.Center; column7.Format.Alignment = ParagraphAlignment.Center; Row row = table.AddRow(); row.Cells[0].AddParagraph("Team left:"); row.Cells[1].AddParagraph(teamLeft); row.Cells[2].AddParagraph(""); row.Cells[3].AddParagraph(""); row.Cells[4].AddParagraph("Team right:"); row.Cells[5].AddParagraph(teamRight); row.Cells[6].AddParagraph(""); row.Cells[7].AddParagraph(""); Row row2 = table.AddRow(); row2.Cells[0].AddParagraph("Playername"); row2.Cells[1].AddParagraph("Role"); row2.Cells[2].AddParagraph("Plays"); row2.Cells[3].AddParagraph("Notes"); row2.Cells[4].AddParagraph("Playername"); row2.Cells[5].AddParagraph("Role"); row2.Cells[6].AddParagraph("Plays"); row2.Cells[7].AddParagraph("Notes"); Row row3 = table.AddRow(); Row row4 = table.AddRow(); Row row5 = table.AddRow(); Row row6 = table.AddRow(); Row row7 = table.AddRow(); Row row8 = table.AddRow(); Row row9 = table.AddRow(); row3.Height = "1.5cm"; row4.Height = "1.5cm"; row5.Height = "1.5cm"; row6.Height = "1.5cm"; row7.Height = "1.5cm"; row8.Height = "1.5cm"; row9.Height = "1.5cm"; var pdfRenderer = new PdfDocumentRenderer(false) { Document = document }; pdfRenderer.RenderDocument(); String pdfName = seasonData.slug + divData.slug + teamLeft + teamRight + matchData.tbp + ".pdf"; String filename = pdfName.Replace(" ", string.Empty).Replace(":", string.Empty).Replace("/", string.Empty).Replace("-", string.Empty); pdfRenderer.PdfDocument.Save(filename); Process.Start(filename); }
/// <summary> /// Export to PDF /// </summary> public void DoExportPDF(string modelNameToExport) { /// This is a bit tricky on non-Windows platforms. /// Normally PdfSharp tries to get a Windows DC for associated font information /// See https://alex-maz.info/pdfsharp_150 for the work-around we can apply here. /// See also http://stackoverflow.com/questions/32726223/pdfsharp-migradoc-font-resolver-for-embedded-fonts-system-argumentexception /// The work-around is to register our own fontresolver. We don't need to do this on Windows. if (Environment.OSVersion.Platform != PlatformID.Win32NT && Environment.OSVersion.Platform != PlatformID.Win32Windows && GlobalFontSettings.FontResolver == null) { GlobalFontSettings.FontResolver = new MyFontResolver(); } // Create a temporary working directory. string workingDirectory = Path.Combine(Path.GetTempPath(), "autodoc"); if (Directory.Exists(workingDirectory)) { Directory.Delete(workingDirectory, true); } Directory.CreateDirectory(workingDirectory); Document document = new Document(); CreatePDFSyles(document); document.DefaultPageSetup.LeftMargin = MigraDoc.DocumentObjectModel.Unit.FromCentimeter(1); document.DefaultPageSetup.TopMargin = MigraDoc.DocumentObjectModel.Unit.FromCentimeter(1); document.DefaultPageSetup.BottomMargin = MigraDoc.DocumentObjectModel.Unit.FromCentimeter(1); Section section = document.AddSection(); // write image files string png1 = Path.Combine(workingDirectory, "AIBanner.png"); using (FileStream file = new FileStream(png1, FileMode.Create, FileAccess.Write)) { Assembly.GetExecutingAssembly().GetManifestResourceStream("ApsimNG.Resources.AIBanner.png").CopyTo(file); } section.AddImage(png1); // Convert all models in file to tags. List <AutoDocumentation.ITag> tags = new List <AutoDocumentation.ITag>(); foreach (IModel child in ExplorerPresenter.ApsimXFile.Children) { AutoDocumentation.DocumentModel(child, tags, headingLevel: 1, indent: 0); if (child.Name == "TitlePage") { AddBackground(tags); AddUserDocumentation(tags, modelNameToExport); // Document model description. int modelDescriptionIndex = tags.Count; tags.Add(new AutoDocumentation.Heading("Model description", 1)); ExplorerPresenter.ApsimXFile.DocumentModel(modelNameToExport, tags, 1); // If no model was documented then remove the 'Model description' tag. if (modelDescriptionIndex == tags.Count - 1) { tags.RemoveAt(modelDescriptionIndex); } } else if (child.Name == "Validation") { AddStatistics(tags); } } // Strip all blank sections i.e. two headings with nothing between them. StripEmptySections(tags); // Scan for citations. ScanForCitations(tags); // Create a bibliography. CreateBibliography(tags); // numebr all headings. NumberHeadings(tags); // Populate the PDF section. TagsToMigraDoc(section, tags, workingDirectory); // Write the PDF file. FileNameWritten = Path.Combine(Path.GetDirectoryName(ExplorerPresenter.ApsimXFile.FileName), modelNameToExport + ".pdf"); PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save(FileNameWritten); // Remove temporary working directory. Directory.Delete(workingDirectory, true); }
/// <summary> /// Creates PDF document from given content. See https://github.com/CommunityHiQ/Frends.Community.PdfFromTemplate /// </summary> /// <param name="outputFile"></param> /// <param name="content"></param> /// <param name="options"></param> /// <returns>Object { bool Success, string FileName, byte[] ResultAsByteArray }</returns> public static Output CreatePdf([PropertyTab] FileProperties outputFile, [PropertyTab] DocumentContent content, [PropertyTab] Options options) { try { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); DocumentDefinition docContent = JsonConvert.DeserializeObject <DocumentDefinition>(content.ContentJson); var document = new Document(); if (!string.IsNullOrWhiteSpace(docContent.Title)) { document.Info.Title = docContent.Title; } if (!string.IsNullOrWhiteSpace(docContent.Author)) { document.Info.Author = docContent.Author; } PageSetup.GetPageSize(docContent.PageSize.ConvertEnum <PageFormat>(), out Unit width, out Unit height); var section = document.AddSection(); SetupPage(section.PageSetup, width, height, docContent); // index for stylename var elementNumber = 0; // add page elements foreach (var pageElement in docContent.DocumentElements) { var styleName = $"style_{elementNumber}"; var style = document.Styles.AddStyle(styleName, "Normal"); switch (pageElement.ElementType) { case ElementTypeEnum.Paragraph: SetFont(style, ((ParagraphDefinition)pageElement).StyleSettings); SetParagraphStyle(style, ((ParagraphDefinition)pageElement).StyleSettings, false); AddTextContent(section, ((ParagraphDefinition)pageElement).Text, style); break; case ElementTypeEnum.Image: AddImage(section, (ImageDefinition)pageElement, width); break; case ElementTypeEnum.Table: SetFont(style, ((TableDefinition)pageElement).StyleSettings); SetParagraphStyle(style, ((TableDefinition)pageElement).StyleSettings, true); AddTable(section, (TableDefinition)pageElement, width, style); break; case ElementTypeEnum.PageBreak: section = document.AddSection(); SetupPage(section.PageSetup, width, height, docContent); break; default: break; } ++elementNumber; } string fileName = Path.Combine(outputFile.Directory, outputFile.FileName); int fileNameIndex = 1; while (File.Exists(fileName) && outputFile.FileExistsAction != FileExistsActionEnum.Overwrite) { switch (outputFile.FileExistsAction) { case FileExistsActionEnum.Error: throw new Exception($"File {fileName} already exists."); case FileExistsActionEnum.Rename: fileName = Path.Combine(outputFile.Directory, $"{Path.GetFileNameWithoutExtension(outputFile.FileName)}_({fileNameIndex}){Path.GetExtension(outputFile.FileName)}"); break; } fileNameIndex++; } // save document var pdfRenderer = new PdfDocumentRenderer(outputFile.Unicode) { Document = document }; pdfRenderer.RenderDocument(); if (outputFile.SaveToDisk) { if (!options.UseGivenCredentials) { pdfRenderer.PdfDocument.Save(fileName); } else { var domainAndUserName = GetDomainAndUserName(options.UserName); using (Impersonation.LogonUser(domainAndUserName[0], domainAndUserName[1], options.Password, LogonType.NewCredentials)) { pdfRenderer.PdfDocument.Save(fileName); } } } byte[] resultAsBytes = null; if (options.GetResultAsByteArray) { using (MemoryStream stream = new MemoryStream()) { pdfRenderer.PdfDocument.Save(stream, false); resultAsBytes = stream.ToArray(); } } return(new Output { Success = true, FileName = fileName, ResultAsByteArray = resultAsBytes }); } catch (Exception ex) { if (options.ThrowErrorOnFailure) { throw; } return(new Output { Success = false, ErrorMessage = ex.Message }); } }
public static void CreateRankingListPDF(Client.DataAccess c, QualificationRoundSet qRnd, List <ComboBoxFlights> qRndFlights, String pathToPDF) { List <Toplist> toplist = new List <Toplist>(); foreach (ComboBoxFlights cbct in qRndFlights) { int sum = 0; foreach (PenaltySet penalty in cbct.flight.PenaltySet) { sum += penalty.Points; } toplist.Add(new Toplist(cbct.flight, sum)); } toplist.Sort(); Document doc = new Document(); doc.Info.Author = "*****@*****.**"; doc.Info.Comment = "Generated from ANRL Client on " + DateTime.Now.ToString(); doc.Info.Keywords = "ANRL Toplist"; doc.Info.Subject = "Toplist"; doc.Info.Title = "Toplist"; doc.UseCmykColor = true; doc.DefaultPageSetup.PageFormat = PageFormat.A4; doc.DefaultPageSetup.Orientation = Orientation.Landscape; doc.DefaultPageSetup.BottomMargin = Unit.FromCentimeter(1); doc.DefaultPageSetup.TopMargin = Unit.FromCentimeter(1); doc.DefaultPageSetup.LeftMargin = Unit.FromCentimeter(1.5); doc.DefaultPageSetup.RightMargin = Unit.FromCentimeter(1); Section sec = doc.AddSection(); AddCompetitionAndLogo(c, sec); sec.AddParagraph(""); sec.AddParagraph("Ranking List: " + qRnd.Name); sec.AddParagraph(""); Table table = sec.AddTable(); table.Borders.Visible = true; table.AddColumn(Unit.FromCentimeter(2)); table.AddColumn(Unit.FromCentimeter(2)); table.AddColumn(Unit.FromCentimeter(2.5)); table.AddColumn(Unit.FromCentimeter(4)); table.AddColumn(Unit.FromCentimeter(4)); table.AddColumn(Unit.FromCentimeter(4)); table.AddColumn(Unit.FromCentimeter(4)); Row row = table.AddRow(); row.Shading.Color = Colors.Gray; row.Cells[0].AddParagraph("Rank"); row.Cells[1].AddParagraph("Points"); row.Cells[2].AddParagraph("Nationality"); row.Cells[3].AddParagraph("Pilot Lastname"); row.Cells[4].AddParagraph("Pilot Firstname"); row.Cells[5].AddParagraph("Navigator Lastname"); row.Cells[6].AddParagraph("Navigator Firstname"); int oldsum = -1; int prevRank = 0; int rank = 0; foreach (Toplist top in toplist) { rank++; TeamSet t = top.ct.TeamSet; Row r = table.AddRow(); if (rank > 1 && oldsum == top.sum) // we have a shared rank { r.Cells[0].AddParagraph(prevRank + ""); } else // the normal case { prevRank = rank; r.Cells[0].AddParagraph(rank + ""); } r.Cells[1].AddParagraph(top.sum.ToString()); r.Cells[2].AddParagraph(t.Nationality); SubscriberSet pilot = t.Pilot; r.Cells[3].AddParagraph(pilot.LastName); r.Cells[4].AddParagraph(pilot.FirstName); if (t.Navigator != null) { SubscriberSet navigator = t.Navigator; r.Cells[5].AddParagraph(navigator.LastName); r.Cells[6].AddParagraph(navigator.FirstName); } oldsum = top.sum; } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(pathToPDF); Process.Start(pathToPDF); }
public static void CreateDoc(PdfInfo info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; foreach (var reception in info.Receptions) { var receptionLabel = section.AddParagraph("Услуга №" + reception.Id + " от " + reception.DateCreate.ToShortDateString()); receptionLabel.Style = "NormalTitle"; receptionLabel.Format.SpaceBefore = "1cm"; receptionLabel.Format.SpaceAfter = "0,25cm"; var servicesLabel = section.AddParagraph("Услуги:"); servicesLabel.Style = "NormalTitle"; var serviceTable = document.LastSection.AddTable(); List <string> headerWidths = new List <string> { "1cm", "3,5cm", "3cm", "3,5cm" }; foreach (var elem in headerWidths) { serviceTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "№", "Название", "Цена", "Количество" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); int i = 1; foreach (var service in reception.ReceptionServices) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { i.ToString(), service.ServiceName, (service.Price * service.Count).ToString(), service.Count.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "Итого:", reception.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); if (reception.ReceptionStatus == ReceptionStatus.Оформлен) { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "К оплате:", reception.TotalSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } else { CreateRow(new PdfRowParameters { Table = serviceTable, Texts = new List <string> { "", "", "К оплате:", reception.LeftSum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); } if (info.Payments[reception.Id].Count == 0) { continue; } var paymentsLabel = section.AddParagraph("Платежи:"); paymentsLabel.Style = "NormalTitle"; var paymentTable = document.LastSection.AddTable(); headerWidths = new List <string> { "1cm", "6cm", "6cm", "3cm" }; foreach (var elem in headerWidths) { paymentTable.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { "№", "Дата", "Сумма" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); i = 1; foreach (var payment in info.Payments[reception.Id]) { CreateRow(new PdfRowParameters { Table = paymentTable, Texts = new List <string> { i.ToString(), payment.DatePayment.ToString(), payment.Sum.ToString() }, Style = "Normal", ParagraphAlignment = ParagraphAlignment.Left }); i++; } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
internal static void CreateStartListPDF(QualificationRoundSet qRnd, Client.DataAccess Client, string pathToPDF) { Document doc = new Document(); doc.Info.Author = "*****@*****.**"; doc.Info.Comment = "Generated from ANRL Client on " + DateTime.Now.ToString(); doc.Info.Keywords = "ANRL Start List"; doc.Info.Subject = "Start List"; doc.Info.Title = "Start List"; doc.UseCmykColor = true; doc.DefaultPageSetup.PageFormat = PageFormat.A4; doc.DefaultPageSetup.Orientation = Orientation.Landscape; Section sec = doc.AddSection(); AddCompetitionAndLogo(Client, sec); sec.AddParagraph("Qualification Round: " + qRnd.Name); sec.AddParagraph("Starting List"); sec.AddParagraph("Printed (UTC): " + System.DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ssZ", DateTimeFormatInfo.InvariantInfo)); sec.AddParagraph(""); Table table = sec.AddTable(); table.Borders.Visible = true; table.AddColumn(Unit.FromCentimeter(1)); table.AddColumn(Unit.FromCentimeter(1)); table.AddColumn(Unit.FromCentimeter(2)); table.AddColumn(Unit.FromCentimeter(9)); table.AddColumn(Unit.FromCentimeter(2.1)); table.AddColumn(Unit.FromCentimeter(2.1)); table.AddColumn(Unit.FromCentimeter(2.1)); table.AddColumn(Unit.FromCentimeter(2.1)); table.AddColumn(Unit.FromCentimeter(2.1)); table.AddColumn(Unit.FromCentimeter(1.3)); Row row = table.AddRow(); row.Shading.Color = Colors.Gray; row.Cells[0].AddParagraph("Start ID"); row.Cells[1].AddParagraph("Crew ID"); row.Cells[2].AddParagraph("AC"); row.Cells[3].AddParagraph("Pilot - Navigator"); row.Cells[4].AddParagraph("Start Planning [UTC]"); row.Cells[5].AddParagraph("End Planning [UTC]"); row.Cells[6].AddParagraph("Take-Off [UTC]"); row.Cells[7].AddParagraph("SP Gate [UTC]"); row.Cells[8].AddParagraph("FP Gate [UTC]"); row.Cells[9].AddParagraph("Route"); foreach (FlightSet ct in qRnd.FlightSet.OrderBy(x => x.TimeTakeOff).ThenBy(x => x.Route)) { Row r = table.AddRow(); if ((table.Rows.Count - 1) % 2 == 0) { r.Shading.Color = Colors.LightGray; } r.Cells[0].AddParagraph(ct.StartID.ToString()); TeamSet teams = ct.TeamSet; r.Cells[1].AddParagraph(teams.CNumber); r.Cells[2].AddParagraph(teams.AC); SubscriberSet pilot = teams.Pilot; if (teams.Navigator != null) { SubscriberSet navigator = teams.Navigator; r.Cells[3].AddParagraph(pilot.LastName + " " + pilot.FirstName + " - " + navigator.LastName + " " + navigator.FirstName); } else { r.Cells[3].AddParagraph(pilot.LastName + " " + pilot.FirstName); } DateTime dt = new DateTime(ct.TimeTakeOff); r.Cells[4].AddParagraph(dt.AddMinutes(-C_Timespan_StartPlanningToTKOF).ToString(C_TimeFormat, DateTimeFormatInfo.InvariantInfo)); r.Cells[5].AddParagraph(dt.AddMinutes(-C_Timespan_EndPlanningToTKOF).ToString(C_TimeFormat, DateTimeFormatInfo.InvariantInfo)); // r.Cells[6].Shading.Color = Colors.LightGray; r.Cells[6].AddParagraph(dt.ToString(C_TimeFormat, DateTimeFormatInfo.InvariantInfo)); r.Cells[7].AddParagraph(new DateTime(ct.TimeStartLine).ToString(C_TimeFormat, DateTimeFormatInfo.InvariantInfo)); r.Cells[8].AddParagraph(new DateTime(ct.TimeEndLine).ToString(C_TimeFormat, DateTimeFormatInfo.InvariantInfo)); r.Cells[9].AddParagraph(Enum.GetName(Route.A.GetType(), ct.Route)); r.Cells[9].Format.Alignment = ParagraphAlignment.Center; } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(pathToPDF); Process.Start(pathToPDF); }
private Document DocumentoEpicrisisGabinete() { Document document = new Document(); if (TxtNumExpediente.Text.Trim() != "") { if (lstConsultasPaciente.Items.Count > 0) { if (oCEmpresa.LeeDatosEmpresa() == true && oCPacientes.LeeDatosPaciente(TxtNumExpediente.Text.Trim()) == true) { Section section = document.AddSection(); #region Encabezado (Fecha, Título, Datos Personales y Detalle Opcional) Table tableHeader = document.LastSection.AddTable(); tableHeader.Borders.Visible = true; tableHeader.Borders.Width = 0; Column columnHeader = tableHeader.AddColumn("8cm"); columnHeader.Format.Alignment = ParagraphAlignment.Right; columnHeader = tableHeader.AddColumn("8cm"); columnHeader.Format.Alignment = ParagraphAlignment.Center; Row rowHeader = tableHeader.AddRow(); tableHeader.AddRow(); tableHeader.AddRow(); tableHeader.AddRow(); #region Fecha Paragraph oParagraphDate = rowHeader.Cells[0].AddParagraph(DateTime.Now.Date.ToLongDateString()); oParagraphDate.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 10); rowHeader.Cells[0].MergeRight = 1; #endregion #region Título rowHeader = tableHeader.AddRow(); rowHeader.Cells[0].MergeRight = 1; Paragraph oParagraphTitle = rowHeader.Cells[0].AddParagraph("Epicrisis"); oParagraphTitle.Format.Alignment = ParagraphAlignment.Center; oParagraphTitle.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 26); #endregion tableHeader.AddRow(); tableHeader.AddRow(); tableHeader.AddRow(); #region Datos Personales (Nombre y Cédula) rowHeader = tableHeader.AddRow(); Paragraph oParagraphNombre = rowHeader.Cells[0].AddParagraph(); FormattedText oFormattedTextNombre = oParagraphNombre.AddFormattedText("Nombre: "); oFormattedTextNombre.Bold = true; oFormattedTextNombre.Font.Name = "Segoe UI"; oFormattedTextNombre.Font.Size = 11; oParagraphNombre.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 9); oParagraphNombre.AddText(oCPacientes.Nombre.Trim() + " " + oCPacientes.Apellidos.Trim()); oParagraphNombre.Format.Alignment = ParagraphAlignment.Left; Paragraph oParagraphCedula = rowHeader.Cells[1].AddParagraph(); FormattedText oFormattedTextCedula = oParagraphCedula.AddFormattedText("Cédula: "); oFormattedTextCedula.Bold = true; oFormattedTextCedula.Font.Name = "Segoe UI"; oFormattedTextCedula.Font.Size = 11; oParagraphCedula.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 9); oParagraphCedula.AddText(oCPacientes.Cedula); oParagraphCedula.Format.Alignment = ParagraphAlignment.Left; #endregion tableHeader.AddRow(); tableHeader.AddRow(); #region Detalle Opcional rowHeader = tableHeader.AddRow(); rowHeader.Cells[0].MergeRight = 1; Paragraph oParagraphDetalleOpcional = rowHeader.Cells[0].AddParagraph(); FormattedText oFormattedDetalleOpcional = oParagraphDetalleOpcional.AddFormattedText(textBox1.Text.Trim()); oFormattedDetalleOpcional.Font.Name = "Arial"; oFormattedDetalleOpcional.Font.Size = 10; oParagraphDetalleOpcional.Format.Alignment = ParagraphAlignment.Left; #endregion tableHeader.AddRow(); tableHeader.AddRow(); tableHeader.AddRow(); #endregion #region Tabla de Datos de Consultas if (rdNoIncluirDetallesConsultas.Checked == false) { Table tableData = document.LastSection.AddTable(); tableData.Borders.Visible = true; tableData.Borders.Width = 0.74; tableData.Borders.Color = new MigraDoc.DocumentObjectModel.Color(192, 80, 77); Column columnData = tableData.AddColumn("2.8cm"); columnData.Format.Alignment = ParagraphAlignment.Center; columnData = tableData.AddColumn("3.5cm"); columnData.Format.Alignment = ParagraphAlignment.Center; columnData = tableData.AddColumn("3.5cm"); columnData.Format.Alignment = ParagraphAlignment.Center; columnData = tableData.AddColumn("3.7cm"); columnData.Format.Alignment = ParagraphAlignment.Center; columnData = tableData.AddColumn("3.7cm"); columnData.Format.Alignment = ParagraphAlignment.Center; Row rowData = tableData.AddRow(); rowData.Borders.Top.Clear(); rowData.Borders.Left.Clear(); rowData.Borders.Right.Clear(); rowData.Borders.Bottom.Width = Unit.FromMillimeter(1); Paragraph oParagraphDataHeader = new Paragraph(); //oParagraphDataHeader = rowData.Cells[0].AddParagraph("Fecha de Consulta"); //oParagraphDataHeader.Format.Font = new MigraDoc.DocumentObjectModel.Font("Times New Roman", 13); //oParagraphDataHeader.Format.Font.Bold = true; oParagraphDataHeader = rowData.Cells[0].AddParagraph("Detalle de la Consulta"); oParagraphDataHeader.Format.Font = new MigraDoc.DocumentObjectModel.Font("Times New Roman", 13); oParagraphDataHeader.Format.Font.Bold = true; oParagraphDataHeader = rowData.Cells[1].AddParagraph("Diagnóstico"); oParagraphDataHeader.Format.Font = new MigraDoc.DocumentObjectModel.Font("Times New Roman", 13); oParagraphDataHeader.Format.Font.Bold = true; oParagraphDataHeader = rowData.Cells[2].AddParagraph("Tratamiento"); oParagraphDataHeader.Format.Font = new MigraDoc.DocumentObjectModel.Font("Times New Roman", 13); oParagraphDataHeader.Format.Font.Bold = true; oParagraphDataHeader = rowData.Cells[3].AddParagraph("Exámenes Prescritos"); oParagraphDataHeader.Format.Font = new MigraDoc.DocumentObjectModel.Font("Times New Roman", 13); oParagraphDataHeader.Format.Font.Bold = true; oParagraphDataHeader = rowData.Cells[4].AddParagraph("Gabinete"); oParagraphDataHeader.Format.Font = new MigraDoc.DocumentObjectModel.Font("Times New Roman", 13); oParagraphDataHeader.Format.Font.Bold = true; Paragraph oParagraphData = new Paragraph(); ArrayList oArregloDetallesConsultaEpicrisis = new ArrayList(); int alternateColor = 0; bool continuar = false; foreach (ListViewItem oItem in lstConsultasPaciente.Items) { if (rdTodas.Checked == true) { continuar = true; } else if (rdSeleccionar.Checked == true) { if (oItem.Checked == true) { continuar = true; } else { continuar = false; } } if (continuar == true) { oArregloDetallesConsultaEpicrisis = oCConsultas.DetallesConsultaEpicrisis(oItem.SubItems[1].Text.Trim()); rowData = tableData.AddRow(); //if (alternateColor == 0) // rowData.Shading.Color = new MigraDoc.DocumentObjectModel.Color(239, 211, 210); //else rowData.Shading.Color = Colors.White; string consultaHeader = Convert.ToDateTime(oItem.SubItems[3].Text).ToShortDateString(); oParagraphData = rowData.Cells[0].AddParagraph(consultaHeader); oParagraphData.Format.Font = new MigraDoc.DocumentObjectModel.Font("Times New Roman", 12); oParagraphData.Format.Font.Bold = true; oParagraphData.Format.Font.Color = new MigraDoc.DocumentObjectModel.Color(36, 64, 97); oParagraphData.Format.Alignment = ParagraphAlignment.Left; rowData.Cells[0].Shading.Color = Colors.White; oParagraphData = rowData.Cells[0].AddParagraph(""); oParagraphData = rowData.Cells[0].AddParagraph(oArregloDetallesConsultaEpicrisis[0].ToString().Trim()); oParagraphData.Format.Font.Bold = false; oParagraphData.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 8); oParagraphData.Format.Alignment = ParagraphAlignment.Left; string oTratamiento = oArregloDetallesConsultaEpicrisis[1].ToString().Trim(); int c = 0; while (oTratamiento.Contains("{") || oTratamiento.Contains("}")) { if (c == 0) { oTratamiento = Metodos_Globales.CortaSeccionDeTexto(oTratamiento, "{", "}", ""); } else { oTratamiento = Metodos_Globales.CortaSeccionDeTexto(oTratamiento, "{", "}", ", "); } c++; } oParagraphData = rowData.Cells[1].AddParagraph(oTratamiento.Trim()); oParagraphData.Format.Font.Bold = false; oParagraphData.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 8); oParagraphData.Format.Alignment = ParagraphAlignment.Left; oParagraphData = rowData.Cells[2].AddParagraph(oArregloDetallesConsultaEpicrisis[2].ToString().Trim()); oParagraphData.Format.Font.Bold = false; oParagraphData.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 8); oParagraphData.Format.Alignment = ParagraphAlignment.Left; string detalleExamen = ""; DataSet ds = oCExamenesConsulta.ConsultarSinParametros(oItem.SubItems[1].Text.Trim()); if (ds != null) { if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow dr in ds.Tables[0].Rows) { if (Convert.ToBoolean(dr[3]) == true) { detalleExamen = "• " + oCExamenesConsulta.NombreExamen(dr[0].ToString().Trim()) + "(" + dr[5].ToString().Trim() + ")."; } else { detalleExamen = "• " + oCExamenesConsulta.NombreExamen(dr[0].ToString().Trim()) + "(\"Pendiente de resultados\")."; } oParagraphData = rowData.Cells[3].AddParagraph(detalleExamen.Trim()); oParagraphData.Format.Font.Bold = false; oParagraphData.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 8); oParagraphData.Format.Alignment = ParagraphAlignment.Left; oParagraphData.AddLineBreak(); } } ds.Dispose(); } string gabinete = ""; DataSet ds1 = oCGabineteConsulta.ConsultarSinParametros(oItem.SubItems[1].Text.Trim()); if (ds1 != null) { if (ds1.Tables[0].Rows.Count > 0) { foreach (DataRow dr in ds1.Tables[0].Rows) { if (Convert.ToBoolean(dr[3]) == true) { gabinete = "• " + oCGabineteConsulta.NombreGabinete(dr[0].ToString().Trim()) + "(" + dr[5].ToString().Trim() + ")."; } else { gabinete = "• " + oCGabineteConsulta.NombreGabinete(dr[0].ToString().Trim()) + "(\"Pendiente de resultados\")."; } oParagraphData = rowData.Cells[4].AddParagraph(gabinete.Trim()); oParagraphData.Format.Font.Bold = false; oParagraphData.Format.Font = new MigraDoc.DocumentObjectModel.Font("Arial", 8); oParagraphData.Format.Alignment = ParagraphAlignment.Left; oParagraphData.AddLineBreak(); } } ds1.Dispose(); } if (alternateColor == 0) { alternateColor = 1; } else { alternateColor = 0; } rowData.Borders.Top.Clear(); rowData.Borders.Left.Clear(); //rowData.Borders.Bottom.Clear(); } } } #endregion #region Agrega Footer Section section2 = document.LastSection; section2.PageSetup.OddAndEvenPagesHeaderFooter = false; HeaderFooter footer = new HeaderFooter(); Paragraph paraFooter = new Paragraph(); MigraDoc.DocumentObjectModel.Font ofont = new MigraDoc.DocumentObjectModel.Font("Arial", 8); paraFooter.AddLineBreak(); ofont.Color = Colors.Black; string nombreEmp = oCEmpleados.ObtieneNombreEmpleado(Program.oIdUsuario); string codEmpleado = oCEmpleados.ObtieneCodigoColegiado(Program.oIdUsuario); string footerText = "________________________________" + Environment.NewLine + nombreEmp.Trim() + Environment.NewLine + "Cód. " + codEmpleado.Trim(); paraFooter.AddFormattedText(footerText, ofont); paraFooter.Format.Alignment = ParagraphAlignment.Right; footer.Add(paraFooter); //section2.Footers.Primary = footer; document.LastSection.Footers.Primary = footer; #endregion #region Crea el documento pdfRenderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); #endregion } } } oDocument = document; return(document); }
private void generatePDFFile() { // Create a MigraDoc document Document doc = new Document(); doc.Info.Title = "Sales Order"; doc.Info.Subject = "Order No:" + oModOrder.GetSetorderno; doc.Info.Author = "B.I.O.App System"; //set page orientation doc.DefaultPageSetup.Orientation = MigraDoc.DocumentObjectModel.Orientation.Portrait; doc.DefaultPageSetup.TopMargin = "7.5cm"; //120 doc.DefaultPageSetup.BottomMargin = "8.5cm"; //150 doc.DefaultPageSetup.LeftMargin = 40; doc.DefaultPageSetup.RightMargin = 40; doc.DefaultPageSetup.HeaderDistance = "1.5cm"; //20 doc.DefaultPageSetup.FooterDistance = "1cm"; //20 MigraDoc.DocumentObjectModel.Style style = doc.Styles["Normal"]; // Because all styles are derived from Normal, the next line changes the // font of the whole document. Or, more exactly, it changes the font of // all styles and paragraphs that do not redefine the font. style.Font.Name = "Verdana"; // Create a new style called Table based on style Normal style = doc.Styles.AddStyle("Table", "Normal"); style.Font.Name = "Verdana"; style.Font.Name = "Arial"; style.Font.Size = 8; // Each MigraDoc document needs at least one section. Section section = doc.AddSection(); // Put 1st logo in the header string logo_lima = Server.MapPath("~/images/" + modCompInfo.GetSetcomp_logo1); MigraDoc.DocumentObjectModel.Shapes.Image image = section.Headers.Primary.AddImage(logo_lima); image.Height = "1cm"; image.LockAspectRatio = true; image.RelativeVertical = RelativeVertical.Line; image.RelativeHorizontal = RelativeHorizontal.Margin; image.Top = ShapePosition.Top; image.Left = ShapePosition.Right; image.WrapFormat.Style = WrapStyle.Through; // Put 2nd logo in the header string logo_mod = Server.MapPath("~/images/" + modCompInfo.GetSetcomp_logo2); MigraDoc.DocumentObjectModel.Shapes.Image image2 = section.Headers.Primary.AddImage(logo_mod); image2.Height = "1cm"; image2.LockAspectRatio = true; image2.RelativeVertical = RelativeVertical.Line; image2.RelativeHorizontal = RelativeHorizontal.Margin; image2.Top = ShapePosition.Top; image2.Left = ShapePosition.Left; image2.WrapFormat.Style = WrapStyle.Through; // Create Header Paragraph header = section.Headers.Primary.AddParagraph(); header.AddText("PESANAN JUALAN"); header.Format.Font.Size = 12; header.Format.Font.Bold = true; header.Format.Alignment = ParagraphAlignment.Center; // Create main section for Sales Order //Paragraph main = section.AddParagraph(); // main = section.AddParagraph(); //main.Format.SpaceBefore = 1; // Create the item table for header //MigraDoc.DocumentObjectModel.Tables.Table tableTop = section.AddTable(); MigraDoc.DocumentObjectModel.Tables.Table tableTop = section.Headers.Primary.AddTable(); tableTop.Style = "Table"; tableTop.Borders.Color = MigraDoc.DocumentObjectModel.Colors.Blue; tableTop.Borders.Width = 0.25; tableTop.Borders.Left.Width = 0.5; tableTop.Borders.Right.Width = 0.5; tableTop.Rows.LeftIndent = 0; // Before you can add a row, you must define the columns Column columnTop = tableTop.AddColumn("8cm"); columnTop.Format.Alignment = ParagraphAlignment.Left; columnTop = tableTop.AddColumn("3cm"); columnTop.Format.Alignment = ParagraphAlignment.Left; columnTop = tableTop.AddColumn("7cm"); columnTop.Format.Alignment = ParagraphAlignment.Left; Row rowTop = tableTop.AddRow(); rowTop.Borders.Left.Visible = false; rowTop.Borders.Right.Visible = false; rowTop.Borders.Top.Visible = false; rowTop.Borders.Bottom.Visible = false; rowTop = tableTop.AddRow(); rowTop.Borders.Left.Visible = false; rowTop.Borders.Right.Visible = false; rowTop.Borders.Top.Visible = false; rowTop.Borders.Bottom.Visible = false; rowTop = tableTop.AddRow(); rowTop.Borders.Left.Visible = false; rowTop.Borders.Right.Visible = false; rowTop.Borders.Top.Visible = false; rowTop.Borders.Bottom.Visible = false; rowTop = tableTop.AddRow(); rowTop.Borders.Left.Visible = false; rowTop.Borders.Right.Visible = false; rowTop.Borders.Top.Visible = false; //rowTop.Borders.Bottom.Visible = false; rowTop.Cells[0].AddParagraph(); rowTop.Cells[0].Borders.Bottom.Visible = false; rowTop.Cells[1].AddParagraph(); rowTop.Cells[2].AddParagraph(); rowTop = tableTop.AddRow(); rowTop.Cells[0].AddParagraph("Daripada:"); rowTop.Cells[0].AddParagraph(modCompInfo.GetSetcomp_name); rowTop.Cells[0].AddParagraph(modCompInfo.GetSetcomp_address); rowTop.Cells[0].AddParagraph(modCompInfo.GetSetcomp_website); rowTop.Cells[0].Borders.Left.Visible = false; rowTop.Cells[0].Borders.Right.Visible = false; rowTop.Cells[0].Borders.Top.Visible = false; rowTop.Cells[0].Borders.Bottom.Visible = false; rowTop.Cells[0].MergeDown = 5; rowTop.Cells[1].AddParagraph("No. Pesanan"); rowTop.Cells[1].Borders.Right.Visible = false; rowTop.Cells[2].AddParagraph(": " + oModOrder.GetSetorderno); rowTop.Cells[2].Borders.Left.Visible = false; rowTop = tableTop.AddRow(); rowTop.Cells[1].AddParagraph("Tarikh"); rowTop.Cells[1].Borders.Right.Visible = false; rowTop.Cells[2].AddParagraph(": " + oModOrder.GetSetorderdate); rowTop.Cells[2].Borders.Left.Visible = false; rowTop = tableTop.AddRow(); rowTop.Cells[1].AddParagraph("Jenis"); rowTop.Cells[1].Borders.Right.Visible = false; rowTop.Cells[2].AddParagraph(": " + oModOrder.GetSetordertype); rowTop.Cells[2].Borders.Left.Visible = false; rowTop = tableTop.AddRow(); rowTop.Cells[1].AddParagraph("Pejabat Jualan"); rowTop.Cells[1].Borders.Right.Visible = false; rowTop.Cells[2].AddParagraph(": " + modCompInfo.GetSetcomp_name); rowTop.Cells[2].Borders.Left.Visible = false; rowTop = tableTop.AddRow(); rowTop.Cells[1].AddParagraph("Pegawai Jualan"); rowTop.Cells[1].Borders.Right.Visible = false; rowTop.Cells[2].AddParagraph(": " + oModOrder.GetSetusername); rowTop.Cells[2].Borders.Left.Visible = false; rowTop = tableTop.AddRow(); rowTop.Cells[0].Borders.Bottom.Visible = false; rowTop.Cells[1].AddParagraph("No. Dihubungi"); rowTop.Cells[1].Borders.Right.Visible = false; rowTop.Cells[2].AddParagraph(": " + modCompInfo.GetSetcomp_contactno); rowTop.Cells[2].Borders.Left.Visible = false; rowTop = tableTop.AddRow(); rowTop.Cells[0].AddParagraph(""); rowTop.Cells[0].MergeRight = 2; rowTop.Cells[0].Borders.Left.Visible = false; rowTop.Cells[0].Borders.Right.Visible = false; rowTop.Cells[0].Borders.Top.Visible = false; rowTop.Cells[0].Borders.Bottom.Visible = false; rowTop.Cells[2].Borders.Right.Visible = false; rowTop = tableTop.AddRow(); rowTop.Cells[0].AddParagraph("Kepada: "); rowTop.Cells[0].AddParagraph(oModOrder.GetSetbpdesc); rowTop.Cells[0].AddParagraph(oModOrder.GetSetbpaddress); rowTop.Cells[0].AddParagraph("Hubungi: " + oModOrder.GetSetbpcontact); rowTop.Cells[0].Borders.Left.Visible = false; rowTop.Cells[0].Borders.Right.Visible = false; rowTop.Cells[0].Borders.Bottom.Visible = false; rowTop.Cells[1].AddParagraph("Support: "); rowTop.Cells[1].AddParagraph(modCompInfo.GetSetcomp_contact); rowTop.Cells[1].AddParagraph("SALES & SUPPORT"); rowTop.Cells[1].AddParagraph("Hubungi: " + modCompInfo.GetSetcomp_contactno); rowTop.Cells[1].Borders.Left.Visible = false; rowTop.Cells[1].Borders.Right.Visible = false; rowTop.Cells[1].Borders.Bottom.Visible = false; rowTop.Cells[1].MergeRight = 1; rowTop.Cells[2].Borders.Right.Visible = false; // Create the item table MigraDoc.DocumentObjectModel.Tables.Table table = section.AddTable(); table.Style = "Table"; table.Borders.Color = MigraDoc.DocumentObjectModel.Colors.Blue; table.Borders.Width = 0.25; table.Borders.Left.Width = 0.5; table.Borders.Right.Width = 0.5; table.Rows.LeftIndent = 0; // Before you can add a row, you must define the columns Column column = table.AddColumn("0.5cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("3cm"); column.Format.Alignment = ParagraphAlignment.Right; column = table.AddColumn("4cm"); column.Format.Alignment = ParagraphAlignment.Right; column = table.AddColumn("2cm"); column.Format.Alignment = ParagraphAlignment.Right; column = table.AddColumn("2cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("1cm"); column.Format.Alignment = ParagraphAlignment.Right; column = table.AddColumn("2cm"); column.Format.Alignment = ParagraphAlignment.Right; column = table.AddColumn("1.5cm"); column.Format.Alignment = ParagraphAlignment.Right; column = table.AddColumn("2cm"); column.Format.Alignment = ParagraphAlignment.Right; // Create the header of the table Row row = table.AddRow(); row.HeadingFormat = true; row.Format.Alignment = ParagraphAlignment.Center; row.Format.Font.Bold = true; row.Shading.Color = MigraDoc.DocumentObjectModel.Colors.LightGray; row.Cells[0].AddParagraph("#"); row.Cells[0].Format.Alignment = ParagraphAlignment.Center; row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[1].AddParagraph("NO. ITEM"); row.Cells[1].Format.Alignment = ParagraphAlignment.Center; row.Cells[1].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[2].AddParagraph("KETERANGAN"); row.Cells[2].Format.Alignment = ParagraphAlignment.Center; row.Cells[2].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[3].AddParagraph("HARGA UNIT"); row.Cells[3].Format.Alignment = ParagraphAlignment.Center; row.Cells[3].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[4].AddParagraph("DISKAUN"); row.Cells[4].Format.Alignment = ParagraphAlignment.Center; row.Cells[4].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[5].AddParagraph("QTY"); row.Cells[5].Format.Alignment = ParagraphAlignment.Center; row.Cells[5].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[6].AddParagraph("HARGA"); row.Cells[6].Format.Alignment = ParagraphAlignment.Center; row.Cells[6].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[7].AddParagraph("TAX"); row.Cells[7].Format.Alignment = ParagraphAlignment.Center; row.Cells[7].VerticalAlignment = VerticalAlignment.Bottom; row.Cells[8].AddParagraph("JUMLAH"); row.Cells[8].Format.Alignment = ParagraphAlignment.Center; row.Cells[8].VerticalAlignment = VerticalAlignment.Bottom; for (int i = 0; i < lsOrderLineItem.Count; i++) { MainModel modOrdDet = (MainModel)lsOrderLineItem[i]; // Each item fills two rows Row row1 = table.AddRow(); row1.Height = "2cm"; row1.TopPadding = 1.5; //row1.Cells[0].VerticalAlignment = VerticalAlignment.Center; row1.Cells[0].Format.Alignment = ParagraphAlignment.Center; row1.Cells[1].Format.Alignment = ParagraphAlignment.Left; row1.Cells[2].Format.Alignment = ParagraphAlignment.Left; row1.Cells[3].Format.Alignment = ParagraphAlignment.Right; row1.Cells[4].Format.Alignment = ParagraphAlignment.Right; row1.Cells[5].Format.Alignment = ParagraphAlignment.Center; row1.Cells[6].Format.Alignment = ParagraphAlignment.Right; row1.Cells[7].Format.Alignment = ParagraphAlignment.Right; row1.Cells[8].Format.Alignment = ParagraphAlignment.Right; row1.Cells[0].AddParagraph((i + 1).ToString()); row1.Cells[1].AddParagraph(modOrdDet.GetSetitemno); row1.Cells[2].AddParagraph(modOrdDet.GetSetitemdesc); row1.Cells[3].AddParagraph(modOrdDet.GetSetunitprice.ToString("#,##0.00")); row1.Cells[4].AddParagraph(modOrdDet.GetSetdiscamount.ToString("#,##0.00")); row1.Cells[5].AddParagraph(modOrdDet.GetSetquantity.ToString()); row1.Cells[6].AddParagraph(modOrdDet.GetSetorderprice.ToString("#,##0.00")); row1.Cells[7].AddParagraph(modOrdDet.GetSettaxamount.ToString("#,##0.00")); row1.Cells[8].AddParagraph(modOrdDet.GetSettotalprice.ToString("#,##0.00")); if (i > 0 && ((i + 1) % 6) == 0) { row1.Cells[0].Borders.Bottom.Visible = true; row1.Cells[1].Borders.Bottom.Visible = true; row1.Cells[2].Borders.Bottom.Visible = true; row1.Cells[3].Borders.Bottom.Visible = true; row1.Cells[4].Borders.Bottom.Visible = true; row1.Cells[5].Borders.Bottom.Visible = true; row1.Cells[6].Borders.Bottom.Visible = true; row1.Cells[7].Borders.Bottom.Visible = true; row1.Cells[8].Borders.Bottom.Visible = true; } else { row1.Cells[0].Borders.Bottom.Visible = false; row1.Cells[1].Borders.Bottom.Visible = false; row1.Cells[2].Borders.Bottom.Visible = false; row1.Cells[3].Borders.Bottom.Visible = false; row1.Cells[4].Borders.Bottom.Visible = false; row1.Cells[5].Borders.Bottom.Visible = false; row1.Cells[6].Borders.Bottom.Visible = false; row1.Cells[7].Borders.Bottom.Visible = false; row1.Cells[8].Borders.Bottom.Visible = false; } } if ((lsOrderLineItem.Count % 6) > 0) { int totalremainingrow = 6 - (lsOrderLineItem.Count % 6); for (int j = 0; j < totalremainingrow; j++) { Row rowRemain = table.AddRow(); rowRemain.Height = "2cm"; rowRemain.Cells[0].AddParagraph(); rowRemain.Cells[1].AddParagraph(); rowRemain.Cells[2].AddParagraph(); rowRemain.Cells[3].AddParagraph(); rowRemain.Cells[4].AddParagraph(); rowRemain.Cells[5].AddParagraph(); rowRemain.Cells[6].AddParagraph(); rowRemain.Cells[7].AddParagraph(); rowRemain.Cells[8].AddParagraph(); if (j == (totalremainingrow - 1)) { rowRemain.Cells[0].Borders.Bottom.Visible = true; rowRemain.Cells[1].Borders.Bottom.Visible = true; rowRemain.Cells[2].Borders.Bottom.Visible = true; rowRemain.Cells[3].Borders.Bottom.Visible = true; rowRemain.Cells[4].Borders.Bottom.Visible = true; rowRemain.Cells[5].Borders.Bottom.Visible = true; rowRemain.Cells[6].Borders.Bottom.Visible = true; rowRemain.Cells[7].Borders.Bottom.Visible = true; rowRemain.Cells[8].Borders.Bottom.Visible = true; } else if (j > 0 && (j % (totalremainingrow - 1)) == 0) { rowRemain.Cells[0].Borders.Bottom.Visible = true; rowRemain.Cells[1].Borders.Bottom.Visible = true; rowRemain.Cells[2].Borders.Bottom.Visible = true; rowRemain.Cells[3].Borders.Bottom.Visible = true; rowRemain.Cells[4].Borders.Bottom.Visible = true; rowRemain.Cells[5].Borders.Bottom.Visible = true; rowRemain.Cells[6].Borders.Bottom.Visible = true; rowRemain.Cells[7].Borders.Bottom.Visible = true; rowRemain.Cells[8].Borders.Bottom.Visible = true; } else { rowRemain.Cells[0].Borders.Bottom.Visible = false; rowRemain.Cells[1].Borders.Bottom.Visible = false; rowRemain.Cells[2].Borders.Bottom.Visible = false; rowRemain.Cells[3].Borders.Bottom.Visible = false; rowRemain.Cells[4].Borders.Bottom.Visible = false; rowRemain.Cells[5].Borders.Bottom.Visible = false; rowRemain.Cells[6].Borders.Bottom.Visible = false; rowRemain.Cells[7].Borders.Bottom.Visible = false; rowRemain.Cells[8].Borders.Bottom.Visible = false; } } } /* * Row rowTax = table.AddRow(); * //rowTax.Height = "1cm"; * rowTax.Cells[0].AddParagraph(); * rowTax.Cells[0].Borders.Left.Visible = false; * rowTax.Cells[0].Borders.Right.Visible = false; * rowTax.Cells[0].Borders.Bottom.Visible = false; * rowTax.Cells[0].MergeRight = 6; * rowTax.Cells[7].AddParagraph("TAX"); * rowTax.Cells[7].Format.Alignment = ParagraphAlignment.Left; * rowTax.Cells[8].AddParagraph(oModOrder.GetSettaxamount.ToString("#,##0.00")); * rowTax.Cells[8].Format.Alignment = ParagraphAlignment.Right; */ Row rowTot = table.AddRow(); rowTot.Height = "1cm"; rowTot.Format.Font.Bold = true; rowTot.Cells[0].AddParagraph(); rowTot.Cells[0].Borders.Left.Visible = false; rowTot.Cells[0].Borders.Right.Visible = false; rowTot.Cells[0].Borders.Bottom.Visible = false; rowTot.Cells[0].MergeRight = 6; /* * rowTot.Cells[1].AddParagraph(); * rowTot.Cells[1].Borders.Left.Visible = false; * rowTot.Cells[2].AddParagraph(); * rowTot.Cells[2].Borders.Left.Visible = false; * rowTot.Cells[3].AddParagraph(); * rowTot.Cells[3].Borders.Left.Visible = false; * rowTot.Cells[4].AddParagraph(); * rowTot.Cells[4].Borders.Left.Visible = false; * rowTot.Cells[5].AddParagraph(); * rowTot.Cells[5].Borders.Left.Visible = false; * rowTot.Cells[6].AddParagraph(); * rowTot.Cells[6].Borders.Left.Visible = false; */ rowTot.Cells[6].Borders.Right.Visible = false; rowTot.Cells[7].AddParagraph("JUMLAH BESAR"); rowTot.Cells[7].Format.Alignment = ParagraphAlignment.Left; rowTot.Cells[7].VerticalAlignment = VerticalAlignment.Center; rowTot.Cells[7].Borders.Left.Visible = false; //rowTot.Cells[7].Borders.Right.Visible = false; rowTot.Cells[7].Borders.Bottom.Visible = false; rowTot.Cells[8].AddParagraph(oModOrder.GetSettotalamount.ToString("#,##0.00")); rowTot.Cells[8].Format.Alignment = ParagraphAlignment.Right; rowTot.Cells[8].VerticalAlignment = VerticalAlignment.Center; //footer.AddText("Footer"); //footer.Format.Font.Size = 9; //footer.Format.Alignment = ParagraphAlignment.Center; // Create the item table for footer //MigraDoc.DocumentObjectModel.Tables.Table tblBtm = section.Headers.Primary.AddImage(logo_lima); MigraDoc.DocumentObjectModel.Tables.Table tblBtm = section.Footers.Primary.AddTable(); //MigraDoc.DocumentObjectModel.Tables.Table tblBtm = section.AddTable(); tblBtm.Style = "Table"; tblBtm.Borders.Color = MigraDoc.DocumentObjectModel.Colors.Blue; tblBtm.Borders.Width = 0.25; tblBtm.Borders.Left.Width = 0.5; tblBtm.Borders.Right.Width = 0.5; tblBtm.Rows.LeftIndent = 0; // Before you can add a row, you must define the columns Column colTblBtm = tblBtm.AddColumn("6cm"); colTblBtm.Format.Alignment = ParagraphAlignment.Left; colTblBtm = tblBtm.AddColumn("6cm"); colTblBtm.Format.Alignment = ParagraphAlignment.Left; colTblBtm = tblBtm.AddColumn("6cm"); colTblBtm.Format.Alignment = ParagraphAlignment.Left; Row rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Left.Visible = false; rowTblBtm.Borders.Right.Visible = false; rowTblBtm.Borders.Top.Visible = false; //rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph("Catatan:"); rowTblBtm.Cells[0].MergeRight = 2; rowTblBtm = tblBtm.AddRow(); //rowTblBtm.Borders.Left.Visible = false; //rowTblBtm.Borders.Right.Visible = false; //rowTblBtm.Borders.Top.Visible = false; rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph(oModOrder.GetSetorderremarks); rowTblBtm.Cells[0].MergeRight = 2; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Height = "2cm"; //rowTblBtm.Borders.Left.Visible = false; //rowTblBtm.Borders.Right.Visible = false; rowTblBtm.Borders.Top.Visible = false; //rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph(); rowTblBtm.Cells[0].MergeRight = 2; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Left.Visible = false; rowTblBtm.Borders.Right.Visible = false; rowTblBtm.Borders.Top.Visible = false; rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph("1. Setelah Pesanan Jualan disahkan, sebarang pembatalan dan perubahan pesanan tidak dibenarkan."); rowTblBtm.Cells[0].MergeRight = 2; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Left.Visible = false; rowTblBtm.Borders.Right.Visible = false; rowTblBtm.Borders.Top.Visible = false; rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph("2. Penghantaran item Pesanan Jualan akan dilakukan setelah menerima pengesahan daripada Pejabat Jualan."); rowTblBtm.Cells[0].MergeRight = 2; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Left.Visible = false; rowTblBtm.Borders.Right.Visible = false; rowTblBtm.Borders.Top.Visible = false; rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph("3. Perubahan pada harga item Pesanan Jualan adalah tertakluk kepada terma & syarat tanpa sebarang notis."); rowTblBtm.Cells[0].MergeRight = 2; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Left.Visible = false; rowTblBtm.Borders.Right.Visible = false; rowTblBtm.Borders.Top.Visible = false; //rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph(); rowTblBtm.Cells[0].MergeRight = 1; rowTblBtm.Cells[2].AddParagraph(); rowTblBtm.Cells[2].Borders.Bottom.Visible = false; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Format.Font.Bold = true; rowTblBtm.Cells[0].AddParagraph(oModOrder.GetSetbpdesc); //rowTblBtm.Cells[0].Borders.Top.Visible = true; rowTblBtm.Cells[1].AddParagraph(modCompInfo.GetSetcomp_name); rowTblBtm.Cells[2].AddParagraph(); rowTblBtm.Cells[2].Borders.Left.Visible = false; rowTblBtm.Cells[2].Borders.Right.Visible = false; rowTblBtm.Cells[2].Borders.Top.Visible = false; rowTblBtm.Cells[2].Borders.Bottom.Visible = false; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph("Disahkan Oleh: (Cop dan Tandatangan)"); rowTblBtm.Cells[1].AddParagraph("Disemak Oleh:"); rowTblBtm.Cells[2].AddParagraph(); rowTblBtm.Cells[2].Borders.Left.Visible = false; rowTblBtm.Cells[2].Borders.Right.Visible = false; rowTblBtm.Cells[2].Borders.Top.Visible = false; rowTblBtm.Cells[2].Borders.Bottom.Visible = false; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[2].Borders.Left.Visible = false; rowTblBtm.Cells[2].Borders.Right.Visible = false; rowTblBtm.Cells[2].Borders.Top.Visible = false; rowTblBtm.Cells[2].Borders.Bottom.Visible = false; rowTblBtm.Height = "2cm"; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph("Nama:"); rowTblBtm.Cells[1].AddParagraph("Nama:"); rowTblBtm.Cells[2].AddParagraph(); rowTblBtm.Cells[2].Borders.Left.Visible = false; rowTblBtm.Cells[2].Borders.Right.Visible = false; rowTblBtm.Cells[2].Borders.Top.Visible = false; rowTblBtm.Cells[2].Borders.Bottom.Visible = false; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Borders.Bottom.Visible = false; rowTblBtm.Cells[0].AddParagraph("Jawatan:"); rowTblBtm.Cells[1].AddParagraph("Jawatan: Pegawai Jualan & Pemasaran"); rowTblBtm.Cells[2].AddParagraph(); rowTblBtm.Cells[2].Borders.Left.Visible = false; rowTblBtm.Cells[2].Borders.Right.Visible = false; rowTblBtm.Cells[2].Borders.Top.Visible = false; rowTblBtm.Cells[2].Borders.Bottom.Visible = false; rowTblBtm = tblBtm.AddRow(); rowTblBtm.Cells[0].AddParagraph("Tarikh:"); rowTblBtm.Cells[1].AddParagraph("Tarikh:"); rowTblBtm.Cells[2].AddParagraph(); rowTblBtm.Cells[2].Borders.Left.Visible = false; rowTblBtm.Cells[2].Borders.Right.Visible = false; rowTblBtm.Cells[2].Borders.Top.Visible = false; rowTblBtm.Cells[2].Borders.Bottom.Visible = false; // Create a renderer for PDF that uses Unicode font encoding PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true); // Set the MigraDoc document pdfRenderer.Document = doc; // Create the PDF document pdfRenderer.RenderDocument(); // Save the document... string pdfFilename = sOrderNo + ".pdf"; string file = Server.MapPath("~/App_Data/" + pdfFilename); //string file = HttpContext.Current.Server.MapPath("~/pdf/" + pdfFilename); //string file = "C:/TEMP/" + pdfFilename; // ...and start a viewer // //pdfRenderer.Save(file); //Process.Start(file); // Send PDF to browser // MemoryStream stream = new MemoryStream(); pdfRenderer.Save(stream, false); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("content-length", stream.Length.ToString()); Response.BinaryWrite(stream.ToArray()); Response.Flush(); stream.Close(); Response.End(); //download file // //Response.ContentType = "Application/pdf"; //Response.AppendHeader("Content-Disposition", "attachment; filename=" + pdfFilename); //Response.TransmitFile(file); //Response.End(); }
public static void createPDF(string stationName, DateTime importNumber, DateTime analysisDate, IList <Transformer> transformers, string evaluation) { try { // Create a MigraDoc document Document document = new Document(); // Each MigraDoc document needs at least one section. Section section = document.AddSection(); // Put a logo in the header Paragraph header = section.Headers.Primary.AddParagraph(); header.AddText("Central Chemical Laboratories"); header.AddLineBreak(); header.AddText("General Management for Oil Analysis"); header.AddLineBreak(); header.AddText("Transformer Oil Testing Laboratory"); header.Format.Font.Size = 12; header.Format.Alignment = ParagraphAlignment.Center; TextFrame titleFrame = section.AddTextFrame(); titleFrame.Height = "1.0cm"; titleFrame.Width = "7.0cm"; titleFrame.Left = ShapePosition.Center; titleFrame.RelativeHorizontal = RelativeHorizontal.Page; //titleFrame.Top = "5.0cm"; //titleFrame.RelativeVertical = RelativeVertical.Page; TextFrame sampleInfoFrame = section.AddTextFrame(); sampleInfoFrame.Height = "3.0cm"; sampleInfoFrame.Width = "7.0cm"; sampleInfoFrame.Left = ShapePosition.Left; sampleInfoFrame.RelativeHorizontal = RelativeHorizontal.Margin; sampleInfoFrame.RelativeVertical = RelativeVertical.Line; Paragraph sampleInfoFrameParagraph = sampleInfoFrame.AddParagraph(); sampleInfoFrameParagraph.Format.Font.Size = 12; sampleInfoFrameParagraph.Format.Font.Bold = true; sampleInfoFrameParagraph.AddText("Sample Source:"); sampleInfoFrameParagraph.AddLineBreak(); sampleInfoFrameParagraph.AddText("Sample Date:"); sampleInfoFrameParagraph.AddLineBreak(); sampleInfoFrameParagraph.AddText("Analysis Date:"); // Create the item table Table table = section.AddTable(); table.Style = "Table"; table.Borders.Width = 0.25; table.Borders.Left.Width = 0.5; table.Borders.Right.Width = 0.5; table.Rows.LeftIndent = 0; // Before you can add a row, you must define the columns Column column; column = table.AddColumn("3.5cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("2.1cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("2.1cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("2.1cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("2.1cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("2.1cm"); column.Format.Alignment = ParagraphAlignment.Center; // Create the header of the table Row row = table.AddRow(); row.HeadingFormat = true; row.Format.Alignment = ParagraphAlignment.Center; row.Format.Font.Bold = true; row.Cells[1].AddParagraph("Standard Method"); row.Cells[1].Format.Alignment = ParagraphAlignment.Center; row.Cells[5].AddParagraph("Acting Test"); row.Cells[5].Format.Alignment = ParagraphAlignment.Center; row.Cells[5].VerticalAlignment = VerticalAlignment.Center; row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Specific Gravity at 15 ºC"); row.Cells[1].AddParagraph("ASTM D1298"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.SG?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.SG?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.SG?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Color"); row.Cells[1].AddParagraph("ASTM D1500"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.COL?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.COL?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.COL?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Water Content ppm at 20 ºC"); row.Cells[1].AddParagraph("BS 148 IEC 60733"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.WA?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.WA?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.WA?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Impurities"); row.Cells[1].AddParagraph("ASTM D1796"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.IMP?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.IMP?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.IMP?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Total Acidity (mg KOH/g oil)"); row.Cells[1].AddParagraph("ASTM D974 IP 1"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.IPI?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.IPI?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.IPI?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Break down Voltage Kv /2.5 mm"); row.Cells[1].AddParagraph("IEC 60156"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.KV?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.KV?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.KV?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Power Factor at 90 ºC"); row.Cells[1].AddParagraph("ASTM D924"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.PF?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.PF?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.PF?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Inter Facial Tension dyne/cm"); row.Cells[1].AddParagraph("ASTM D971"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.ST?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.ST?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.ST?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Kinematics Viscosity (CST) at 40 ºC"); row.Cells[1].AddParagraph("ASTM D445"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.KI?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.KI?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.KI?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Flash Point open ºC"); row.Cells[1].AddParagraph("ASTM D92"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.FL?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.FL?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.FL?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Copper Corrosion"); row.Cells[1].AddParagraph("ASTM D130"); // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(transformers[1]?.CO?.ToString()); row.Cells[3].AddParagraph(transformers[2]?.CO?.ToString()); row.Cells[4].AddParagraph(transformers[3]?.CO?.ToString()); row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Cells[0].AddParagraph("Evaluation"); row.Cells[1].MergeRight = 4; // row.Cells[2] : row.Cells[5] data row.Cells[2].AddParagraph(evaluation); row.Cells[3].AddParagraph(evaluation); row.Cells[4].AddParagraph(evaluation); TextFrame signatureFrame = section.AddTextFrame(); signatureFrame.Left = ShapePosition.Center; signatureFrame.RelativeHorizontal = RelativeHorizontal.Margin; signatureFrame.RelativeVertical = RelativeVertical.Line; Paragraph signatureFrameParagraph = signatureFrame.AddParagraph(); signatureFrameParagraph.Format.Font.Size = 12; signatureFrameParagraph.Format.Font.Bold = true; signatureFrameParagraph.AddText(" Manager of General Manager"); signatureFrameParagraph.AddLineBreak(); signatureFrameParagraph.AddText("Transformer Oils Lab of Oil Analysis Department\n"); document.UseCmykColor = true; // Create a renderer for PDF that uses Unicode font encoding PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true); // Set the MigraDoc document pdfRenderer.Document = document; // Create the PDF document pdfRenderer.RenderDocument(); // Save the PDF document... string filename = "Report.pdf"; // I don't want to close the document constantly... filename = "Report" + Guid.NewGuid().ToString("N").ToUpper() + ".pdf"; pdfRenderer.Save(filename); // ...and start a viewer. Process.Start(filename); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } }
/// <summary> /// Print an order to PDF /// </summary> /// <param name="order">Order</param> /// <param name="languageId">Language identifier</param> /// <param name="filePath">File path</param> public static void PrintOrderToPdf(Order order, int languageId, string filePath) { if (order == null) { throw new ArgumentNullException("order"); } if (String.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } Document doc = new Document(); Section sec = doc.AddSection(); Table table = sec.AddTable(); table.Borders.Visible = false; bool logoExists = File.Exists(PDFHelper.LogoFilePath); table.AddColumn(Unit.FromCentimeter(10)); if (logoExists) { table.AddColumn(Unit.FromCentimeter(10)); } Row ordRow = table.AddRow(); int rownum = logoExists ? 1 : 0; Paragraph p1 = ordRow[rownum].AddParagraph(String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Order#", languageId), order.OrderId)); p1.Format.Font.Bold = true; p1.Format.Font.Color = Colors.Black; ordRow[rownum].AddParagraph(SettingManager.StoreUrl.Trim(new char[] { '/' })).AddHyperlink(SettingManager.StoreUrl, HyperlinkType.Url); ordRow[rownum].AddParagraph(String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.OrderDate", languageId), order.CreatedOn)); if (File.Exists(PDFHelper.LogoFilePath)) { ordRow[0].AddImage(PDFHelper.LogoFilePath); } var addressTable = sec.AddTable(); if (order.ShippingStatus != ShippingStatusEnum.ShippingNotRequired) { addressTable.AddColumn(Unit.FromCentimeter(9)); addressTable.AddColumn(Unit.FromCentimeter(9)); } else { addressTable.AddColumn(Unit.FromCentimeter(18)); } addressTable.Borders.Visible = false; Row row = addressTable.AddRow(); //billing info row.Cells[0].AddParagraph(); Paragraph p2 = row.Cells[0].AddParagraph(LocalizationManager.GetLocaleResourceString("PDFInvoice.BillingInformation", languageId)); p2.Format.Font.Bold = true; p2.Format.Font.Color = Colors.Black; if (!String.IsNullOrEmpty(order.BillingCompany)) { row.Cells[0].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Company", languageId), order.BillingCompany)); } row.Cells[0].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Name", languageId), order.BillingFullName)); row.Cells[0].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Phone", languageId), order.BillingPhoneNumber)); if (!String.IsNullOrEmpty(order.BillingFaxNumber)) { row.Cells[0].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Fax", languageId), order.BillingFaxNumber)); } row.Cells[0].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Address", languageId), order.BillingAddress1)); if (!String.IsNullOrEmpty(order.BillingAddress2)) { row.Cells[0].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Address2", languageId), order.BillingAddress2)); } row.Cells[0].AddParagraph(" " + String.Format("{0}, {1}", order.BillingCountry, order.BillingStateProvince)); row.Cells[0].AddParagraph(" " + String.Format("{0}, {1}", order.BillingCity, order.BillingZipPostalCode)); row.Cells[0].AddParagraph(); //shipping info if (order.ShippingStatus != ShippingStatusEnum.ShippingNotRequired) { row.Cells[1].AddParagraph(); Paragraph p3 = row.Cells[1].AddParagraph(LocalizationManager.GetLocaleResourceString("PDFInvoice.ShippingInformation", languageId)); p3.Format.Font.Bold = true; p3.Format.Font.Color = Colors.Black; if (!String.IsNullOrEmpty(order.ShippingCompany)) { row.Cells[1].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Company", languageId), order.ShippingCompany)); } row.Cells[1].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Name", languageId), order.ShippingFullName)); row.Cells[1].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Phone", languageId), order.ShippingPhoneNumber)); if (!String.IsNullOrEmpty(order.ShippingFaxNumber)) { row.Cells[1].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Fax", languageId), order.ShippingFaxNumber)); } row.Cells[1].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Address", languageId), order.ShippingAddress1)); if (!String.IsNullOrEmpty(order.ShippingAddress2)) { row.Cells[1].AddParagraph(" " + String.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.Address2", languageId), order.ShippingAddress2)); } row.Cells[1].AddParagraph(" " + String.Format("{0}, {1}", order.ShippingCountry, order.ShippingStateProvince)); row.Cells[1].AddParagraph(" " + String.Format("{0}, {1}", order.ShippingCity, order.ShippingZipPostalCode)); row.Cells[1].AddParagraph(); } sec.AddParagraph(); //products Paragraph p4 = sec.AddParagraph(LocalizationManager.GetLocaleResourceString("PDFInvoice.Product(s)", languageId)); p4.Format.Font.Bold = true; p4.Format.Font.Color = Colors.Black; sec.AddParagraph(); var productCollection = order.OrderProductVariants; var tbl = sec.AddTable(); tbl.Borders.Visible = true; tbl.Borders.Width = 1; tbl.AddColumn(Unit.FromCentimeter(8)); tbl.AddColumn(Unit.FromCentimeter(4)); tbl.AddColumn(Unit.FromCentimeter(2)); tbl.AddColumn(Unit.FromCentimeter(4)); Row header = tbl.AddRow(); header.Cells[0].AddParagraph(LocalizationManager.GetLocaleResourceString("PDFInvoice.ProductName", languageId)); header.Cells[0].Format.Alignment = ParagraphAlignment.Center; header.Cells[1].AddParagraph(LocalizationManager.GetLocaleResourceString("PDFInvoice.ProductPrice", languageId)); header.Cells[1].Format.Alignment = ParagraphAlignment.Center; header.Cells[2].AddParagraph(LocalizationManager.GetLocaleResourceString("PDFInvoice.ProductQuantity", languageId)); header.Cells[2].Format.Alignment = ParagraphAlignment.Center; header.Cells[3].AddParagraph(LocalizationManager.GetLocaleResourceString("PDFInvoice.ProductTotal", languageId)); header.Cells[3].Format.Alignment = ParagraphAlignment.Center; for (int i = 0; i < productCollection.Count; i++) { var orderProductVariant = productCollection[i]; int rowNum = i + 1; Row prodRow = tbl.AddRow(); string name = String.Format("Not available. Id={0}", orderProductVariant.ProductVariantId); var pv = ProductManager.GetProductVariantById(orderProductVariant.ProductVariantId); if (pv != null) { name = pv.FullProductName; } prodRow.Cells[0].AddParagraph(name); Paragraph p5 = prodRow.Cells[0].AddParagraph(HtmlHelper.ConvertHtmlToPlainText(orderProductVariant.AttributeDescription, true)); p5.Format.Font.Italic = true; prodRow.Cells[0].Format.Alignment = ParagraphAlignment.Left; string unitPrice = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayTypeEnum.ExcludingTax: unitPrice = PriceHelper.FormatPrice(orderProductVariant.UnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, false); break; case TaxDisplayTypeEnum.IncludingTax: unitPrice = PriceHelper.FormatPrice(orderProductVariant.UnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, true); break; } prodRow.Cells[1].AddParagraph(unitPrice); prodRow.Cells[2].AddParagraph(orderProductVariant.Quantity.ToString()); string subTotal = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayTypeEnum.ExcludingTax: subTotal = PriceHelper.FormatPrice(orderProductVariant.PriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, false); break; case TaxDisplayTypeEnum.IncludingTax: subTotal = PriceHelper.FormatPrice(orderProductVariant.PriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, true); break; } prodRow.Cells[3].AddParagraph(subTotal); } //checkout attributes if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription)) { sec.AddParagraph(); Paragraph pCheckoutAttributes = null; string attributes = HtmlHelper.ConvertHtmlToPlainText(order.CheckoutAttributeDescription, true); pCheckoutAttributes = sec.AddParagraph(attributes); if (pCheckoutAttributes != null) { pCheckoutAttributes.Format.Alignment = ParagraphAlignment.Right; } } //subtotal sec.AddParagraph(); Paragraph p6 = null; switch (order.CustomerTaxDisplayType) { case TaxDisplayTypeEnum.ExcludingTax: { string orderSubtotalExclTaxStr = PriceHelper.FormatPrice(order.OrderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, false); p6 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.Sub-Total", languageId), orderSubtotalExclTaxStr)); } break; case TaxDisplayTypeEnum.IncludingTax: { string orderSubtotalInclTaxStr = PriceHelper.FormatPrice(order.OrderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, true); p6 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.Sub-Total", languageId), orderSubtotalInclTaxStr)); } break; } if (p6 != null) { p6.Format.Alignment = ParagraphAlignment.Right; } //discount if (order.OrderDiscountInCustomerCurrency > decimal.Zero) { string orderDiscountInCustomerCurrencyStr = PriceHelper.FormatPrice(-order.OrderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false); Paragraph p7 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.Discount", languageId), orderDiscountInCustomerCurrencyStr)); p7.Format.Alignment = ParagraphAlignment.Right; } //shipping if (order.ShippingStatus != ShippingStatusEnum.ShippingNotRequired) { Paragraph p9 = null; switch (order.CustomerTaxDisplayType) { case TaxDisplayTypeEnum.ExcludingTax: { string orderShippingExclTaxStr = PriceHelper.FormatShippingPrice(order.OrderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, false); p9 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.Shipping", languageId), orderShippingExclTaxStr)); } break; case TaxDisplayTypeEnum.IncludingTax: { string orderShippingInclTaxStr = PriceHelper.FormatShippingPrice(order.OrderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, true); p9 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.Shipping", languageId), orderShippingInclTaxStr)); } break; } if (p9 != null) { p9.Format.Alignment = ParagraphAlignment.Right; } } //payment fee if (order.PaymentMethodAdditionalFeeExclTaxInCustomerCurrency > decimal.Zero) { Paragraph p10 = null; switch (order.CustomerTaxDisplayType) { case TaxDisplayTypeEnum.ExcludingTax: { string paymentMethodAdditionalFeeExclTaxStr = PriceHelper.FormatPaymentMethodAdditionalFee(order.PaymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, false); p10 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.PaymentMethodAdditionalFee", languageId), paymentMethodAdditionalFeeExclTaxStr)); } break; case TaxDisplayTypeEnum.IncludingTax: { string paymentMethodAdditionalFeeInclTaxStr = PriceHelper.FormatPaymentMethodAdditionalFee(order.PaymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, NopContext.Current.WorkingLanguage, true); p10 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.PaymentMethodAdditionalFee", languageId), paymentMethodAdditionalFeeInclTaxStr)); } break; } if (p10 != null) { p10.Format.Alignment = ParagraphAlignment.Right; } } //tax string taxStr = string.Empty; bool displayTax = true; if (TaxManager.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayTypeEnum.IncludingTax) { displayTax = false; } else { if (order.OrderTax == 0 && TaxManager.HideZeroTax) { displayTax = false; } else { taxStr = PriceHelper.FormatPrice(order.OrderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false); } } if (displayTax) { var p11 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.Tax", languageId), taxStr)); p11.Format.Alignment = ParagraphAlignment.Right; } //gift cards var gcuhC = OrderManager.GetAllGiftCardUsageHistoryEntries(null, null, order.OrderId); foreach (var giftCardUsageHistory in gcuhC) { string gcTitle = string.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.GiftCardInfo", languageId), giftCardUsageHistory.GiftCard.GiftCardCouponCode); string gcAmountStr = PriceHelper.FormatPrice(-giftCardUsageHistory.UsedValueInCustomerCurrency, true, order.CustomerCurrencyCode, false); Paragraph p8 = sec.AddParagraph(String.Format("{0} {1}", gcTitle, gcAmountStr)); p8.Format.Alignment = ParagraphAlignment.Right; } //reward points if (order.RedeemedRewardPoints != null) { string rpTitle = string.Format(LocalizationManager.GetLocaleResourceString("PDFInvoice.RewardPoints", languageId), -order.RedeemedRewardPoints.Points); string rpAmount = PriceHelper.FormatPrice(-order.RedeemedRewardPoints.UsedAmountInCustomerCurrency, true, order.CustomerCurrencyCode, false); var p11 = sec.AddParagraph(String.Format("{0} {1}", rpTitle, rpAmount)); p11.Format.Alignment = ParagraphAlignment.Right; } //order total string orderTotalStr = PriceHelper.FormatPrice(order.OrderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false); var p12 = sec.AddParagraph(String.Format("{0} {1}", LocalizationManager.GetLocaleResourceString("PDFInvoice.OrderTotal", languageId), orderTotalStr)); p12.Format.Font.Bold = true; p12.Format.Font.Color = Colors.Black; p12.Format.Alignment = ParagraphAlignment.Right; PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(filePath); }
public static void CreateDoc(PdfInfoClient info) { Document document = new Document(); DefineStyles(document); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(info.Title); paragraph.Format.SpaceAfter = "1cm"; paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "NormalTitle"; paragraph = section.AddParagraph($"с {info.DateFrom.ToShortDateString()} по { info.DateTo.ToShortDateString()}"); paragraph.Format.SpaceAfter = "1cm"; paragraph.Format.Alignment = ParagraphAlignment.Center; paragraph.Style = "Normal"; var table = document.LastSection.AddTable(); List <string> columns = new List <string> { "3cm", "6cm", "3cm", "2cm", "3cm" }; foreach (var elem in columns) { table.AddColumn(elem); } CreateRow(new PdfRowParameters { Table = table, Texts = new List <string> { "Дата заказа", "Изделие", "Количество", "Сумма", "Статус" }, Style = "NormalTitle", ParagraphAlignment = ParagraphAlignment.Center }); decimal sumOrder = 0; // foreach (var order in info.Orders) // { // CreateRow(new PdfRowParameters // { // Table = table, // Texts = new List<string> { order.DateCreate.ToShortDateString(), //order.ManufactureName, order.Count.ToString(), order.Sum.ToString(), order.Status.ToString() //}, // Style = "Normal", // ParagraphAlignment = ParagraphAlignment.Left // }); // sumOrder += order.Sum; // } Paragraph paragraphSum = section.AddParagraph($"Итого:{sumOrder.ToString()}"); paragraphSum.Format.SpaceAfter = "4cm"; paragraphSum.Format.Alignment = ParagraphAlignment.Right; PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always) { Document = document }; renderer.RenderDocument(); renderer.PdfDocument.Save(info.FileName); }
/// <summary> /// Print product collection to PDF /// </summary> /// <param name="productCollection"></param> /// <param name="filePath"></param> public static void PrintProductsToPdf(ProductCollection productCollection, string filePath) { if (String.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } Document doc = new Document(); Section section = doc.AddSection(); int productNumber = 1; int prodCount = productCollection.Count; foreach (var product in productCollection) { Paragraph p1 = section.AddParagraph(String.Format("{0}. {1}", productNumber, product.Name)); p1.Format.Font.Bold = true; p1.Format.Font.Color = Colors.Black; section.AddParagraph(); section.AddParagraph(HtmlHelper.StripTags(HtmlHelper.ConvertHtmlToPlainText(product.FullDescription))); section.AddParagraph(); var productPictureCollection = product.ProductPictures; if (productPictureCollection.Count > 0) { Table table = section.AddTable(); table.Borders.Visible = false; table.AddColumn(Unit.FromCentimeter(10)); table.AddColumn(Unit.FromCentimeter(10)); Row row = table.AddRow(); for (int i = 0; i < productPictureCollection.Count; i++) { int cellNum = i % 2; var pic = productPictureCollection[i].Picture; if (pic != null && pic.PictureBinary != null && pic.PictureBinary.Length > 0) { row.Cells[cellNum].AddImage(PictureManager.GetPictureLocalPath(pic, 200, true)); } if (i != 0 && i % 2 == 0) { row = table.AddRow(); } } section.AddParagraph(); } int pvNum = 1; foreach (var productVariant in product.ProductVariants) { string pvName = String.IsNullOrEmpty(productVariant.Name) ? LocalizationManager.GetLocaleResourceString("PDFProductCatalog.UnnamedProductVariant") : productVariant.Name; section.AddParagraph(String.Format("{0}.{1}. {2}", productNumber, pvNum, pvName)); section.AddParagraph(); if (!String.IsNullOrEmpty(productVariant.Description)) { section.AddParagraph(HtmlHelper.StripTags(HtmlHelper.ConvertHtmlToPlainText(productVariant.Description))); section.AddParagraph(); } var pic = productVariant.Picture; if (pic != null && pic.PictureBinary != null && pic.PictureBinary.Length > 0) { section.AddImage(PictureManager.GetPictureLocalPath(pic, 200, true)); } section.AddParagraph(String.Format("{0}: {1} {2}", LocalizationManager.GetLocaleResourceString("PDFProductCatalog.Price"), productVariant.Price, CurrencyManager.PrimaryStoreCurrency.CurrencyCode)); section.AddParagraph(String.Format("{0}: {1}", LocalizationManager.GetLocaleResourceString("PDFProductCatalog.SKU"), productVariant.SKU)); if (productVariant.Weight > Decimal.Zero) { section.AddParagraph(String.Format("{0}: {1} {2}", LocalizationManager.GetLocaleResourceString("PDFProductCatalog.Weight"), productVariant.Weight, MeasureManager.BaseWeightIn.Name)); } if (productVariant.ManageInventory == (int)ManageInventoryMethodEnum.ManageStock) { section.AddParagraph(String.Format("{0}: {1}", LocalizationManager.GetLocaleResourceString("PDFProductCatalog.StockQuantity"), productVariant.StockQuantity)); } section.AddParagraph(); pvNum++; } productNumber++; if (productNumber <= prodCount) { section.AddPageBreak(); } } PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always); renderer.Document = doc; renderer.RenderDocument(); renderer.PdfDocument.Save(filePath); }
/// <summary> /// Asynchronical version of <see cref="PdfDataExporter.Export(IEasyDataResultSet,Stream, IDataExportSettings)" /> method. /// </summary> /// <param name="data">The fetched data.</param> /// <param name="stream">The stream.</param> /// <param name="settings">The settings.</param> /// <returns>Task.</returns> public async Task ExportAsync(IEasyDataResultSet data, Stream stream, IDataExportSettings settings) { var mappedSettings = MapSettings(settings); var document = new Document(); document.Info.Title = settings.Title; ApplyStyles(document, mappedSettings); var section = document.AddSection(); if (settings.ShowDatasetInfo) { // TODO: render paragrap with info here if (!string.IsNullOrWhiteSpace(mappedSettings.Title)) { var p = section.AddParagraph(); p.Format.Alignment = ParagraphAlignment.Center; p.Format.Font.Bold = true; p.AddText(mappedSettings.Title); } if (!string.IsNullOrWhiteSpace(mappedSettings.Description)) { var p = section.AddParagraph(); p.Format.Alignment = ParagraphAlignment.Left; p.AddText(mappedSettings.Description); } } section.AddParagraph(); // Create the item table var table = section.AddTable(); table.Style = "Table"; table.Borders.Color = Color.FromRgb(0, 0, 0); table.Borders.Width = 0.25; table.Borders.Left.Width = 0.5; table.Borders.Right.Width = 0.5; table.Rows.LeftIndent = 0; // filling columns //ignored columns var ignoredCols = GetIgnoredColumns(data, settings); int colsCount = 0; for (int i = 0; i < data.Cols.Count; i++) { if (ignoredCols.Contains(i)) { continue; } var column = table.AddColumn(Unit.FromCentimeter(3)); column.Format.Alignment = ParagraphAlignment.Center; colsCount++; } // filling rows if (settings.ShowColumnNames) { var row = table.AddRow(); row.HeadingFormat = true; row.Format.Alignment = ParagraphAlignment.Center; row.Format.Font.Bold = true; row.Shading.Color = Color.FromRgb(0, 191, 255); for (int i = 0; i < data.Cols.Count; i++) { if (ignoredCols.Contains(i)) { continue; } var colName = data.Cols[i].Label; row.Cells[i].AddParagraph(colName); row.Cells[i].Format.Font.Bold = false; row.Cells[i].Format.Alignment = ParagraphAlignment.Center; row.Cells[i].VerticalAlignment = VerticalAlignment.Center; } table.SetEdge(0, 0, colsCount, 1, Edge.Box, BorderStyle.Single, 0.75, Color.Empty); } // filling rows var rows = data.Rows.Where(row => { var add = settings?.RowFilter?.Invoke(row); if (add.HasValue && !add.Value) { return(false); } return(true); }).ToList(); Task WriteRowAsync(EasyDataRow row, bool isExtra = false) { var pdfRow = table.AddRow(); pdfRow.TopPadding = 1.5; for (int i = 0; i < row.Count; i++) { if (ignoredCols.Contains(i)) { continue; } var col = data.Cols[i]; var dfmt = col.DisplayFormat; var type = col.Type; var s = Utils.GetFormattedValue(row[i], type, mappedSettings, dfmt); pdfRow.Cells[i].Shading.Color = Color.FromRgb(255, 255, 255); pdfRow.Cells[i].VerticalAlignment = VerticalAlignment.Center; pdfRow.Cells[i].Format.Alignment = MapAlignment(col.Style.Alignment); pdfRow.Cells[i].Format.FirstLineIndent = 1; pdfRow.Cells[i].Format.Font.Bold = isExtra; pdfRow.Cells[i].AddParagraph(s); table.SetEdge(0, 1, colsCount, 1, Edge.Box, BorderStyle.Single, 0.75); } return(Task.CompletedTask); } Func <EasyDataRow, Task> WriteExtraRowAsync = (extraRow) => WriteRowAsync(extraRow, true); foreach (var row in rows) { if (mappedSettings.BeforeRowAdded != null) { await mappedSettings.BeforeRowAdded(row, WriteExtraRowAsync); } await WriteRowAsync(row); } if (mappedSettings.BeforeRowAdded != null) { await mappedSettings.BeforeRowAdded(null, WriteExtraRowAsync); } // rendering pdf var pdfRenderer = new PdfDocumentRenderer(true); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); using (MemoryStream memoryStream = new MemoryStream()) { pdfRenderer.PdfDocument.Save(memoryStream, false); memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(stream).ConfigureAwait(false); } }
/// <summary> /// Tests borders. /// </summary> public static void Borders(string outputFile) { Document document = new Document(); Section section = document.AddSection(); Paragraph par = section.AddParagraph(); FillFormattedParagraph(par); GiveBorders(par); PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = document; renderer.RenderDocument(); renderer.PdfDocument.Save(outputFile); }
private static string CreatePdfItemTable(Packliste packliste) { var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temp.pdf"; var document = new Document(); var page = document.AddSection(); page.PageSetup.LeftMargin = 45; page.PageSetup.RightMargin = 45; page.PageSetup.PageFormat = PageFormat.A4; var font = new Font("Arial", 22) { Bold = true }; var headParagraph = page.AddParagraph(); headParagraph.Format.SpaceAfter = 12; headParagraph.AddFormattedText($"{packliste.PacklisteDate:yyyy-MM-dd} \t\tMiddle parts shipment", font); var table = page.AddTable(); table.Borders.Width = 0.5; table.BottomPadding = 2; table.TopPadding = 2; var column = table.AddColumn("8.5cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("6cm"); column.Format.Alignment = ParagraphAlignment.Center; font.Size = 18; font.Bold = true; var row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Format.Font = font.Clone(); row.Cells[0].AddParagraph("Item number"); row.Cells[1].AddParagraph("Quantity"); font.Size = 16; font.Bold = false; foreach (var data in packliste.ItemsWithQties) { row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Center; row.Format.Font = font.Clone(); row.Cells[0].AddParagraph(data.Item.ItemName); row.Cells[1].AddParagraph($"{data.Quantity:N}"); } var renderer = new PdfDocumentRenderer { Document = document }; renderer.RenderDocument(); renderer.Save(path); return(path); }
/// <summary> /// Export to PDF /// </summary> public void DoExportPDF(string modelNameToExport) { // Create a temporary working directory. string workingDirectory = Path.Combine(Path.GetTempPath(), "autodoc"); if (Directory.Exists(workingDirectory)) { Directory.Delete(workingDirectory, true); } Directory.CreateDirectory(workingDirectory); Document document = new Document(); CreatePDFSyles(document); Section section = document.AddSection(); // write image files string png1 = Path.Combine(workingDirectory, "AIBanner.png"); using (FileStream file = new FileStream(png1, FileMode.Create, FileAccess.Write)) { Assembly.GetExecutingAssembly().GetManifestResourceStream("ApsimNG.Resources.AIBanner.png").CopyTo(file); } section.AddImage(png1); List <AutoDocumentation.ITag> tags = new List <AutoDocumentation.ITag>(); // See if there is a title page. If so do it first. IModel titlePage = Apsim.Find(ExplorerPresenter.ApsimXFile, "TitlePage"); if (titlePage != null) { titlePage.Document(tags, 1, 0); } AddBackground(tags); // See if there is a title page. If so do it first. IModel introductionPage = Apsim.Find(ExplorerPresenter.ApsimXFile, "Introduction"); if (introductionPage != null) { tags.Add(new AutoDocumentation.Heading("Introduction", 1)); introductionPage.Document(tags, 1, 0); } // Document model description. tags.Add(new AutoDocumentation.Heading("Model description", 1)); ExplorerPresenter.ApsimXFile.DocumentModel(modelNameToExport, tags, 1); // Document model validation. AddValidationTags(tags, ExplorerPresenter.ApsimXFile, 1, workingDirectory); // Move cultivars to end. MoveCultivarsToEnd(tags); // Strip all blank sections i.e. two headings with nothing between them. StripEmptySections(tags); // Scan for citations. ScanForCitations(tags); // Create a bibliography. CreateBibliography(tags); // numebr all headings. NumberHeadings(tags); // Populate the PDF section. TagsToMigraDoc(section, tags, workingDirectory); // Write the PDF file. FileNameWritten = Path.Combine(Path.GetDirectoryName(ExplorerPresenter.ApsimXFile.FileName), modelNameToExport + ".pdf"); PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false, PdfSharp.Pdf.PdfFontEmbedding.Always); pdfRenderer.Document = document; /// Fails on non-Windows platforms. It's trying to get a Windows DC for associated font information /// See https://alex-maz.info/pdfsharp_150 for a sort of work-around /// See also http://stackoverflow.com/questions/32726223/pdfsharp-migradoc-font-resolver-for-embedded-fonts-system-argumentexception pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save(FileNameWritten); // Remove temporary working directory. Directory.Delete(workingDirectory, true); }
private static string CreatePdf(ICollection <PacklisteData> packlisteData) { var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temp.pdf"; var document = new Document(); var page = document.AddSection(); page.PageSetup.LeftMargin = 40; //page.PageSetup.RightMargin = 40; var titleParagraph = page.AddParagraph(); titleParagraph.Format.Alignment = ParagraphAlignment.Center; titleParagraph.Format.Font = new Font("Courier New", 12); titleParagraph.Format.SpaceAfter = 6; titleParagraph.Format.Font.Bold = true; var headParagraph = page.AddParagraph(); headParagraph.Format.SpaceAfter = 18; headParagraph.Format.Font = new Font("Courier New", 9); headParagraph.Format.TabStops.ClearAll(); headParagraph.Format.TabStops.AddTabStop(30); headParagraph.Format.TabStops.AddTabStop(250); headParagraph.Format.TabStops.AddTabStop(300); var table = page.AddTable(); var column = table.AddColumn("2.5cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("7.8cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("3.8cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("1.5cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("1.5cm"); column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("1.5cm"); column.Format.Alignment = ParagraphAlignment.Left; var lineCount = packlisteData.Last().RowNumber; var headContent = new StringBuilder(); var headerFont = new Font(); //First line is the line where items list start for (var i = 1; i <= packlisteData.First().RowNumber - 1; i++) { var iLine = packlisteData.Where(l => l.RowNumber == i).ToList(); if (!iLine.Any()) { headContent.AppendLine(); continue; } for (var j = 0; j < iLine.Count(); j++) { var rowData = iLine[j]; var isDate = DateTime.TryParse(rowData.Data, out var result); var newLine = isDate ? result.ToShortDateString() : rowData.Data; switch (rowData.ColumnNumber) { case 2: headParagraph.AddTab(); headParagraph.AddText(newLine); break; case 5: titleParagraph.AddText(newLine); break; case 11: if (j == 0) { headParagraph.AddTab(); } headParagraph.AddTab(); headParagraph.AddTab(); headParagraph.AddText(newLine); break; case 13: headParagraph.AddTab(); headParagraph.AddTab(); headParagraph.AddTab(); headParagraph.AddText(newLine); break; default: headParagraph.AddFormattedText(newLine, new Font("Courier New", 9)); break; } if (j + 1 == iLine.Count) { headParagraph.AddChar('\n'); } } } var first = true; var itemCol = 0; var descCol = 0; var reqCol = 0; var ordCol = 0; var qtyCol = 0; for (var i = packlisteData.First().RowNumber; i <= lineCount; i++) { var iLine = packlisteData.Where(l => l.RowNumber == i).ToList(); if (iLine.Count == 0) { continue; } if (first) { var row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Left; row.Format.Font = new Font("Courier New", 8); row.Cells[0].AddParagraph(iLine[1].Data); row.Cells[1].AddParagraph(iLine[2].Data); row.Cells[2].AddParagraph(iLine[4].Data); row.Cells[3].AddParagraph(iLine[5].Data); row.Cells[4].AddParagraph(iLine[6].Data); itemCol = iLine[1].ColumnNumber; descCol = iLine[2].ColumnNumber; reqCol = iLine[4].ColumnNumber; ordCol = iLine[5].ColumnNumber; qtyCol = iLine[6].ColumnNumber; first = false; } else { var row = table.AddRow(); row.Format.Alignment = ParagraphAlignment.Left; row.Format.Font = new Font("Courier New", 8); row.Cells[0].AddParagraph(iLine.Find(c => c.ColumnNumber == itemCol).Data); row.Cells[1].AddParagraph(iLine.Find(c => c.ColumnNumber == descCol).Data); row.Cells[2].AddParagraph(iLine.Find(c => c.ColumnNumber == reqCol).Data); row.Cells[3].AddParagraph(iLine.Find(c => c.ColumnNumber == ordCol).Data); row.Cells[4].AddParagraph(iLine.Find(c => c.ColumnNumber == qtyCol).Data); } } var pdfRenderer = new PdfDocumentRenderer { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save(path); return(path); }
/// <summary> /// Tests document fields. /// </summary> public static void Fields(string outputFile) { Document document = new Document(); Section section = document.AddSection(); Paragraph par = section.AddParagraph(); par.AddText("Section: "); par.AddSectionField().Format = "ALPHABETIC"; par.AddLineBreak(); par.AddText("SectionPages: "); par.AddSectionField().Format = "alphabetic"; par.AddLineBreak(); par.AddText("Page: "); par.AddPageField().Format = "ROMAN"; par.AddLineBreak(); par.AddText("NumPages: "); par.AddNumPagesField(); par.AddLineBreak(); par.AddText("Date: "); par.AddDateField(); par.AddLineBreak(); par.AddText("Bookmark: "); par.AddBookmark("Egal"); par.AddLineBreak(); par.AddText("PageRef: "); par.AddPageRefField("Egal"); PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = document; renderer.RenderDocument(); renderer.PdfDocument.Save(outputFile); }
public Object DownloadMeta(int id, int userid) { FolderDAO folderDAO = new FolderDAO(); FileDAO fileDAO = new FileDAO(); var allfolders = folderDAO.GetAll(); var folders = (from folder in allfolders where folder.CreatedBy == userid select folder).ToList(); var allfiles = fileDAO.GetAll(); var files = (from file in allfiles where file.CreatedBy == userid select file).ToList(); Folder currentFolder = null; if (id == -1) { currentFolder = new Folder(); currentFolder.Id = -1; } else { currentFolder = (from folder in folders where folder.Id == id select folder).FirstOrDefault(); if (currentFolder == null) { return(new HttpResponseMessage(HttpStatusCode.NotFound));; } } Document document = new Document(); Section section = document.AddSection(); TraverseFolders(currentFolder, ref folders, ref files, ref section); PdfDocumentRenderer pdf = new PdfDocumentRenderer(false, PdfSharp.Pdf.PdfFontEmbedding.Always); pdf.Document = document; pdf.RenderDocument(); var rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles"); var uid = Guid.NewGuid() + ".pdf"; var fileSavePath = Path.Combine(rootPath, uid); pdf.PdfDocument.Save(fileSavePath); HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK); byte[] fileStream = System.IO.File.ReadAllBytes(fileSavePath); System.IO.File.Delete(fileSavePath); System.IO.MemoryStream ms = new MemoryStream(fileStream); resp.Content = new ByteArrayContent(fileStream); resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); var type = MimeTypeMap.GetMimeType(".pdf"); resp.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(type); resp.Content.Headers.ContentDisposition.FileName = "meta-data.pdf"; return(resp); }
/// <summary> /// Tests alignments. /// </summary> public static void Alignment(string pdfOutputFile) { Document document = new Document(); Section section = document.AddSection(); section.PageSetup.LeftMargin = 0; section.PageSetup.RightMargin = 0; Paragraph par = section.AddParagraph(); // FillFormattedParagraph(par); // par.Format.Alignment = ParagraphAlignment.Left; // par = section.AddParagraph(); // FillFormattedParagraph(par); // par.Format.Alignment = ParagraphAlignment.Right; // par = section.AddParagraph(); FillFormattedParagraph(par); par.Format.Alignment = ParagraphAlignment.Center; // // par = section.AddParagraph(); // FillFormattedParagraph(par); // par.Format.Alignment = ParagraphAlignment.Justify; par.Format.FirstLineIndent = "-2cm"; par.Format.LeftIndent = "2cm"; par.Format.RightIndent = "3cm"; PdfDocumentRenderer renderer = new PdfDocumentRenderer(); renderer.Document = document; renderer.RenderDocument(); renderer.PdfDocument.Save(pdfOutputFile); }
/// <summary> /// Initializate collections in case if we need name of one of them /// </summary> /// <param name="transFunc">Use delegate for translation method wich work with localResource file</param> /// <param name="paymentMethods"></param> /// <param name="solicitors"></param> /// <param name="mailings"></param> /// <param name="departments"></param> /// <param name="categoryTree"></param> public byte[] CreateDocument(object docObj) { PdfDocumentDto doc = (PdfDocumentDto)docObj; var filter = doc.Filter; var countTrans = doc.CountTrans; var grouped = doc.Grouped; // Create a new MigraDoc document _document = new Document { Info = { Title = filter.Name } }; DefineStyles(); if (filter.view == TransFilterView.Details) { var colsCount = CreatePage(filter, countTrans); if (string.Equals(filter.subtotalBy, "None", StringComparison.InvariantCultureIgnoreCase)) { FillContent(colsCount, grouped.GroupedObj, filter); } else { FillGroupedContent(colsCount, grouped.GroupedObj, filter); } } if (filter.view == TransFilterView.Total) { if (string.Equals(filter.totalOnlyBy, "totalOnly", StringComparison.InvariantCultureIgnoreCase)) { CreatePage(filter, countTrans); if (string.Equals(filter.subtotalBy, "None", StringComparison.InvariantCultureIgnoreCase)) { FillTotalContent(grouped, filter); } if (!string.Equals(filter.subtotalBy, "None", StringComparison.InvariantCultureIgnoreCase)) { FillSubGroupedTotalContent(grouped, filter); } } else { if (filter.ReportType == TransFilterType.Payment) { FillMatrixRows((MatrixDTO)grouped, filter, countTrans); } } } // FillContent(colsCount); PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true); pdfRenderer.Document = _document; pdfRenderer.RenderDocument(); using (MemoryStream ms = new MemoryStream()) { pdfRenderer.Save(ms, false); byte[] buffer = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Flush(); ms.Read(buffer, 0, (int)ms.Length); ms.Close(); return(buffer); } }