public byte[] PrintInventoryPendingLinePdf(IList <InventoryPendingLine> list) { if (list == null) { throw new ArgumentNullException("list"); } byte[] bytes; using (var stream = new MemoryStream()) { Document doc = new Document(PageSize.A4, 20f, 20f, 20f, 20f); PdfWriter writer = PdfWriter.GetInstance(doc, stream); doc.Open(); Font titleFont = FontFactory.GetFont(FontFactory.HELVETICA, 10f, Font.BOLD); Font itemTitle = FontFactory.GetFont(FontFactory.HELVETICA, 10f, Font.BOLD); Font itemFont = FontFactory.GetFont(FontFactory.HELVETICA, 10f); Chunk titleText = new Chunk("Pending Lines", titleFont); LineSeparator firstPageUnderLine = new LineSeparator(0.5f, 100f, BaseColor.BLACK, Element.ALIGN_LEFT, -5f); doc.Add(titleText); doc.Add(firstPageUnderLine); // Items doc.Add(GenerateItems(itemTitle, itemFont, list)); doc.Close(); bytes = stream.ToArray(); } return(bytes); }
public void PrintBranchPendingLinePdf(Stream stream, IList <BranchPendingLineDownload> list) { if (stream == null) { throw new ArgumentNullException("stream"); } if (list == null) { throw new ArgumentNullException("list"); } Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 20f, 20f); PdfWriter pdf = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); Font titleFont = FontFactory.GetFont(FontFactory.HELVETICA, 10f, Font.BOLD); Font itemTitle = FontFactory.GetFont(FontFactory.HELVETICA, 10f, Font.BOLD); //Font addressFont = FontFactory.GetFont(FontFactory.HELVETICA, 9f); Font itemFont = FontFactory.GetFont(FontFactory.HELVETICA, 10f); Chunk titleText = new Chunk("Pending Note", titleFont); //Phrase lineBreak = new Phrase(Environment.NewLine); LineSeparator firstPageUnderLine = new LineSeparator(0.5f, 100f, BaseColor.BLACK, Element.ALIGN_LEFT, -5f); //LineSeparator underLine = new LineSeparator(0.5f, 100f, BaseColor.BLACK, Element.ALIGN_LEFT, -10f); pdfDoc.Add(titleText); pdfDoc.Add(firstPageUnderLine); // Items pdfDoc.Add(GenerateItems(itemTitle, itemFont, list)); pdfDoc.Close(); }
public virtual void CreatePdf(String dest) { PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); Document document = new Document(pdf); SolidLine line = new SolidLine(1f); line.SetColor(ColorConstants.RED); LineSeparator ls = new LineSeparator(line); ls.SetWidth(UnitValue.CreatePercentValue(50)); ls.SetMarginTop(5); IList <IList <String> > resultSet = CsvTo2DList.Convert(SRC, "|"); resultSet.RemoveAt(0); foreach (IList <String> record in resultSet) { String url = String.Format("http://www.imdb.com/title/tt{0}", record[0]); Link movie = new Link(record[2], PdfAction.CreateURI(url)); Div div = new Div().SetKeepTogether(true).SetBorderLeft(new SolidBorder(2)).SetPaddingLeft(3).SetMarginBottom (10).Add(new Paragraph(movie.SetFontSize(14f))).Add(new Paragraph(String.Format("Directed by {0} ({1}, {2})" , record[3], record[4], record[1]))); FileInfo file = new FileInfo(String.Format("../../../resources/img/{0}.jpg", record[0])); if (file.Exists) { iText.Layout.Element.Image img = new Image(ImageDataFactory.Create(file.FullName)); img.ScaleToFit(10000, 120); div.Add(img); } div.Add(ls); document.Add(div); } document.Close(); }
// ****************************************************************** public static List <string[]> ParseString(string[] lines) { List <string[]> result = new List <string[]>(); LineSeparator lineSeparator = LineSeparator.Unknown; if (lines.Any()) { lineSeparator = GuessCsvSeparator(lines[0]); } Func <string, string[]> funcParse = DictionaryOfLineSeparatorAndItsFunc[lineSeparator]; foreach (string line in lines) { if (string.IsNullOrWhiteSpace(line)) { continue; } result.Add(funcParse(line)); } return(result); }
public void IniciarFila() {// Linea Separadora LineSeparator ls = new LineSeparator(new SolidLine()); document.Add(ls); table = new Table(5, false); Cell cell11 = new Cell() .SetBackgroundColor(ColorConstants.GRAY) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("Estado")); Cell cell12 = new Cell() .SetBackgroundColor(ColorConstants.GRAY) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("Sector")); Cell cell13 = new Cell() .SetBackgroundColor(ColorConstants.GRAY) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("TiempoMax")); Cell cell14 = new Cell() .SetBackgroundColor(ColorConstants.GRAY) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("TiempoMin")); Cell cell15 = new Cell() .SetBackgroundColor(ColorConstants.GRAY) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("TiempoProm")); table.AddCell(cell11); table.AddCell(cell12); table.AddCell(cell13); table.AddCell(cell14); table.AddCell(cell15); document.Add(table); }
/// <summary> /// Parses the provided lines of text with the specified line separator. /// <para>If the line separator is unknown, it is determined by the max median of occurences in all of the lines.</para> /// </summary> /// <param name="lines">Lines of text to parse.</param> /// <param name="lineSeparator">The type of delimiter between data segments in a line.</param> public static IEnumerable <string[]> Parse(IEnumerable <string> lines, LineSeparator lineSeparator) { if (lineSeparator == LineSeparator.Unknown) { return(ParseUnknown(lines)); } return(ParseKnown(lines, lineSeparator)); }
/// <summary> /// Parses the provided line separated with the specified line separator. /// <para>If the line separator is unknown, it is set to the one with the max count.</para> /// </summary> /// <param name="line">The line of text to parse.</param> /// <param name="lineSeparator">The type of delimiter between data segments in a line.</param> public static string[] ParseLine(string line, LineSeparator lineSeparator) { if (lineSeparator == LineSeparator.Unknown) { return(ParseLineUnknown(line)); } return(ParseLineKnown(line, lineSeparator)); }
/// <summary> /// Returns true if the given input returns a line or column separator character /// </summary> /// <param name="input"></param> /// <returns></returns> public bool ContainsSeparators(string input) { if (string.IsNullOrEmpty(input)) { return(false); } return(input.Contains(ColumnSeparator) || input.IndexOfAny(LineSeparator.ToCharArray()) >= 0); }
private void addseparater(Document document) { LineSeparator lineSeparator = new LineSeparator(); lineSeparator.LineColor = new iTextSharp.text.Color(0, 0, 100); addlinr(document); document.Add(new Chunk(lineSeparator)); addlinr(document); }
private static IEnumerable <string[]> ParseKnown(IEnumerable <string> lines, LineSeparator lineSeparator) { Regex regex = separatorToRegex[lineSeparator]; foreach (string line in lines) { yield return(ParseLine(line, regex)); } }
//Crear PDF y plantilla correspondiente public void crearEncabezadoPDF() { //Variables string paciente = txtNombre.Text; string edad = txtEdad.Text; string recomendaciones = txt_Recomendaciones.Text; //Concatenaciones string datoNombrePaciente = lb_NombrePaciente.Text + paciente; string datoEdadPaciente = lb_Edad.Text + edad; string datoRecomendaciones = lb_Recomendaciones.Text + recomendaciones; string ruta = string.Format(@"PacientesEjercicios\{0}.pdf", txtNombre.Text); PdfWriter writer = new PdfWriter(ruta); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf); document.SetMargins(20f, 20f, 20f, 20f); //Agregamos Logo de la Clinica Image img = new Image(ImageDataFactory .Create(@"Recursos\LogoCraf.jpg")) .SetTextAlignment(TextAlignment.LEFT) .ScaleToFit(250f, 250f); document.Add(img); //Titulo del documento Paragraph header = new Paragraph("Centro de Rehabilitación Acuática y Fisica") .SetTextAlignment(TextAlignment.RIGHT) .SetFontSize(15); document.Add(header); //Insertamos linea de separacion LineSeparator ls = new LineSeparator(new SolidLine()); document.Add(ls); //Agregamos datos del paciente Paragraph paciente_dato = new Paragraph(datoNombrePaciente).SetTextAlignment(TextAlignment.LEFT).SetFontSize(10); Paragraph edad_dato = new Paragraph(datoEdadPaciente).SetTextAlignment(TextAlignment.LEFT).SetFontSize(10); Paragraph recomendacion_dato = new Paragraph(datoRecomendaciones).SetTextAlignment(TextAlignment.LEFT).SetFontSize(10); document.Add(paciente_dato); document.Add(edad_dato); document.Add(recomendacion_dato); document.Add(ls); //Agregamos las imagenes seleccionadas con los textos //Cerramos documento document.Close(); //Habilitamos el boton visualizar al momento de crear el Pdf btn_Visualizar.Enabled = true; }
public void NuevaLineaDivisoria() { var linea = new LineSeparator(); var espacio = new Chunk(" ", FontFactory.GetFont(FontFactory.HELVETICA, 4)); document.Add(new Paragraph(espacio)); document.Add(linea); document.Add(new Paragraph(espacio)); }
private void AddLineSeparator(Document document) { LineSeparator lineSeparator = new LineSeparator(); lineSeparator.LineColor = new Color(0, 0, 0, 68); AddLineSpace(document); document.Add(new Chunk(lineSeparator)); AddLineSpace(document); }
public void GenerateDocument(Venda venda) { try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch { Messages.ShowError("Falha ao criar o diretório.\nPor favor, tente novamente\n\nSe o problema persistir, crie \"C:\\Temp\\"); return; } PdfWriter writer = new PdfWriter(path + name); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf); Paragraph header = new Paragraph(Properties.Settings.Default.HEADER) .SetTextAlignment(TextAlignment.CENTER) .SetFontSize(15).SetBold(); Paragraph subheader = new Paragraph(Properties.Settings.Default.SUBHEADER) .SetTextAlignment(TextAlignment.CENTER) .SetFontSize(12); Paragraph subheader1 = new Paragraph(Properties.Settings.Default.SUBHEADER1) .SetTextAlignment(TextAlignment.CENTER) .SetFontSize(12); Paragraph subheader2 = new Paragraph(Properties.Settings.Default.SUBHEADER2) .SetTextAlignment(TextAlignment.CENTER) .SetFontSize(12); LineSeparator ls = new LineSeparator(new SolidLine()); PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); float[] cells = { 10, 45, 11f, 18f, 10f, 15f }; Table theader = GenerateHeader(font, cells, Border.NO_BORDER, venda); float[] cellItens = { 10, 5, 5, 50, 15, 15 }; Table itensHeader = GenerateItensHeader(font, cellItens, Border.NO_BORDER); Table itens = GenerateItens(font, cellItens, Border.NO_BORDER, venda); float[] cellDetails = { 85, 15 }; Table details = GenerateDetails(font, cellDetails, Border.NO_BORDER, venda); Table detailsDate = GenerateDetailsDate(font, cellDetails, Border.NO_BORDER, venda); document.Add(header) .Add(subheader) .Add(subheader1) .Add(subheader2) .Add(ls) .Add(theader) .Add(ls) .Add(itensHeader) .Add(ls) .Add(itens) .Add(ls) .Add(details) .Add(ls) .Add(detailsDate); document.Close(); }
public static void GeneratePdfReport(string pageTitle, string pageUrl, Analyzer analyzer) { try { var date = DateTime.Now.ToString("dd-MM-yyyy hh-mm"); var filepath = ConfigurationManager.AppSettings["reportsFolder"]; var fileName = CleanFileName($"{pageTitle} - {date}.pdf"); var fs = new FileStream(filepath + "\\" + fileName, FileMode.Create); var document = new Document(PageSize.A4, 25, 25, 30, 30); var writer = PdfWriter.GetInstance(document, fs); document.AddAuthor("SEO Audit Tool"); document.AddKeywords("On-page SEO report"); document.AddTitle($"Report for: {pageUrl} {Environment.NewLine}"); document.Open(); var header = new Header("header", $"Report for: {pageUrl} {Environment.NewLine}Date: {DateTime.Now:dd-MM-yyyy hh:mm}"); document.Add(header); var firstParagraph = new Paragraph("Search Engine Optimization Report"); firstParagraph.Alignment = 1; firstParagraph.SpacingAfter = 10; LineSeparator separator = new LineSeparator(); var pageParagraph = new Paragraph($"Page: {analyzer.GetPageUrl()}"); var keywordParagraph = new Paragraph($"Keyword: {analyzer.GetKeyword()}"); PdfPTable table = new PdfPTable(2); table.SpacingBefore = 20; table.AddCell("Keyword in title"); table.AddCell(analyzer.KeywordInTitle ? "Found" : "Not found"); table.AddCell("Keyword in description"); table.AddCell(analyzer.KeywordInDescription ? "Found" : "Not found"); table.AddCell("Keyword in headings"); table.AddCell(analyzer.KeywordInHeadings ? "Found" : "Not found"); table.AddCell("Keyword in URL"); table.AddCell(analyzer.KeywordInUrl ? "Found" : "Not found"); document.Add(firstParagraph); document.Add(separator); document.Add(pageParagraph); document.Add(keywordParagraph); document.Add(table); document.Close(); writer.Close(); fs.Close(); } catch (Exception exception) { Console.WriteLine(exception.StackTrace); } }
private string ReceiveEndingsSeparated(string receivedData, string previouslyReceivedData) { bool receivedEndsWithNewline = LineSeparator.Any(lineEnding => receivedData.LastIndexOf(lineEnding) == receivedData.Length - 1); bool startsWithNewline = LineSeparator.Any(lineEnding => receivedData[0] == lineEnding); //separate the lines received string[] lines = receivedData.Split(LineSeparator, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 0) { lines = new string[] { string.Empty } } ; foreach (var ll in lines) { m_Log.Trace("line:{0}", ll); } List <string> receivedLines = new List <string>(); if (startsWithNewline) { if (!string.IsNullOrEmpty(previouslyReceivedData)) { receivedLines.Add(previouslyReceivedData); previouslyReceivedData = string.Empty; } } for (int lineCounter = 0; lineCounter < lines.Length - 1; lineCounter++) { receivedLines.Add(previouslyReceivedData + lines[lineCounter]); previouslyReceivedData = string.Empty; } if (receivedEndsWithNewline) { receivedLines.Add(previouslyReceivedData + lines[lines.Length - 1]); previouslyReceivedData = string.Empty; } else { previouslyReceivedData = previouslyReceivedData + lines[lines.Length - 1]; } foreach (string line in receivedLines) { if (!string.IsNullOrEmpty(line)) { m_Log.Trace("displayed:{0}", line); OnLineReceived(line); } } m_Log.Trace("previously:{0}", previouslyReceivedData); return(previouslyReceivedData); }
/* (non-Javadoc) * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document) */ public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent) { try { IList <IElement> list = new List <IElement>(); HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx); LineSeparator lineSeparator = (LineSeparator)GetCssAppliers().Apply(new LineSeparator(), tag, htmlPipelineContext); list.Add(lineSeparator); return(list); } catch (NoCustomContextException e) { throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e); } }
public static void ExportPurchaseOrders(DataTable dt, string Date) { try { SaveFileDialog sfd = new SaveFileDialog { Filter = "PDF (*.pdf)|*.pdf", FileName = RandomString(5) + DateTime.Now.ToShortDateString().Replace("/", "") }; if (sfd.ShowDialog() == DialogResult.OK) { string fileName = sfd.FileName; PdfWriter writer = new PdfWriter(sfd.FileName); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf, iText.Kernel.Geom.PageSize.A4); Paragraph header = new Paragraph("Ordered Items").SetTextAlignment(TextAlignment.CENTER).SetFontSize(15); Paragraph subheader = new Paragraph("Oder due date : " + Date).SetTextAlignment(TextAlignment.CENTER).SetFontSize(12); Paragraph dl = new Paragraph(". .").SetTextAlignment(TextAlignment.CENTER).SetFontSize(10).SetFontColor(ColorConstants.WHITE); LineSeparator ls = new LineSeparator(new SolidLine()); document.Add(header); document.Add(subheader); document.Add(ls); document.Add(dl); int FontSize = 10; Table table = new Table(3, false); table.SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.CENTER); table.SetVerticalAlignment(VerticalAlignment.TOP); table.AddHeaderCell("Item Code").SetFontSize(FontSize); table.AddHeaderCell("Item Name").SetFontSize(FontSize); table.AddHeaderCell("Quantity").SetFontSize(FontSize); foreach (DataRow d in dt.Rows) { table.AddCell(new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).SetFontSize(FontSize).Add(new Paragraph(d[0].ToString()))); table.AddCell(new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).SetFontSize(FontSize).Add(new Paragraph(d[1].ToString()))); table.AddCell(new Cell(1, 1).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(FontSize).Add(new Paragraph(d[2].ToString()))); } int TotalOrderedQty = GetDTIntegerSum(dt, 2); table.AddFooterCell(new Cell(1, 1).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(FontSize).Add(new Paragraph(string.Empty))); table.AddFooterCell(new Cell(1, 1).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(FontSize).Add(new Paragraph("Total Ordered Quantity"))); table.AddFooterCell(new Cell(1, 1).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(FontSize).Add(new Paragraph(TotalOrderedQty.ToString()))); document.Add(table); document.Close(); StartProcess(fileName); } } catch (Exception ex) { Mes(ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { // Bold BaseFont bf_bold = BaseFont.CreateFont(HttpContext.Current.Server.MapPath("fonts/angsa.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); h1 = new Font(bf_bold, 18); bold = new Font(bf_bold, 16); smallBold = new Font(bf_bold, 14); // Normal BaseFont bf_normal = BaseFont.CreateFont(HttpContext.Current.Server.MapPath("fonts/angsa.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); normal = new Font(bf_normal, 16); smallNormal = new Font(bf_normal, 14); try { // Create PDF document Document pdfDoc = new Document(PageSize.A4, 30, 30, 20, 20); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); pdfDoc.Add(GetHeader()); pdfDoc.Add(GetHeaderDetail()); LineSeparator line = new LineSeparator(); pdfDoc.Add(line); pdfDoc.Add(GetBodyHeader()); pdfDoc.Add(GetBody()); pdfDoc.Add(GetActivities()); pdfDoc.Add(GetBodyFooter()); GetSignature(pdfDoc); pdfDoc.NewPage(); pdfDoc.Add(GetStudentList()); pdfWriter.CloseStream = false; pdfDoc.Close(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment; filename = Example.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Write(pdfDoc); Response.End(); } catch (Exception ex) { Response.Write(ex.Message); } }
public static void ExportListPDF <T>(Dictionary <string, List <T> > individualList, string outputPath) { string PrintDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); // Must have write permissions to the path folder PdfWriter writer = new PdfWriter(outputPath); PdfDocument pdf = new PdfDocument(writer); pdf.SetDefaultPageSize(PageSize.A4.Rotate()); Document document = new Document(pdf); individualList.Keys.ToList().ForEach(key => { // Title PdfFont Titlefont = PdfFontFactory.CreateFont(@"C:\windows\fonts\msjh.ttc,0", PdfEncodings.IDENTITY_H, false); int TitlefontSize = 20; Paragraph header = new Paragraph($"撿貨單") .SetTextAlignment(TextAlignment.CENTER) .SetUnderline() .SetFont(Titlefont).SetFontSize(TitlefontSize); document.Add(header); //subItemTable PdfFont subItemfont = PdfFontFactory.CreateFont(@"C:\windows\fonts\msjh.ttc,0", PdfEncodings.IDENTITY_H, false); int subItemfontSize = 12; Table subItemTable = new Table(1, true); Cell cell13 = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .SetBorder(Border.NO_BORDER) .Add(new Paragraph($"列印日期: {PrintDate}") .SetFont(subItemfont).SetFontSize(subItemfontSize)); subItemTable.AddCell(cell13); document.Add(subItemTable); // Line separator LineSeparator ls = new LineSeparator(new SolidLine(4)); document.Add(ls); document.Add(individualList[key].ToPdfPTable()); //插入分頁 document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE)); }); //拿掉最後一頁空白 pdf.RemovePage(individualList.Keys.Count + 1); document.Close(); }
/// <summary> /// Retrieve the list of risky characters according to this settings definition /// </summary> /// <returns></returns> public char[] GetRiskyChars() { var riskyChars = new List <char>(); riskyChars.Add(FieldDelimiter); riskyChars.Add(TextQualifier); foreach (var c in LineSeparator.ToCharArray()) { riskyChars.Add(c); } // CRLF is always considered risky riskyChars.Add('\n'); riskyChars.Add('\r'); return(riskyChars.ToArray()); }
private Table CreateSeparator(string txt, PdfFont font) { txt = " " + txt + " "; int txtLength = txt.Length; DottedLine dots = new DottedLine(); dots.SetGap((float)0.5); dots.SetLineWidth(1); LineSeparator line = new LineSeparator(dots).SetMarginTop(8); float sepPer; float txtPer; if (txtLength < 12) { sepPer = 45; txtPer = 10; } else if (txtLength < 22) { sepPer = 40; txtPer = 20; } else if (txtLength < 32) { sepPer = 35; txtPer = 30; } else { sepPer = 30; txtPer = 40; } UnitValue[] colVals = new UnitValue[] { UnitValue.CreatePercentValue(sepPer), UnitValue.CreatePercentValue(txtPer), UnitValue.CreatePercentValue(sepPer) }; Table sep = new Table(colVals).UseAllAvailableWidth() .AddCell(new Cell(1, 1).Add(line).SetBorder(Border.NO_BORDER)) .AddCell(new Cell(1, 1).Add(new Paragraph(txt)).SetBorder(Border.NO_BORDER)) .AddCell(new Cell(1, 1).Add(line).SetBorder(Border.NO_BORDER)) .SetTextAlignment(TextAlignment.CENTER) .SetFont(font) .SetFontSize(12); return(sep); }
public static void ExportListPDF <T>(List <T> DataList, string outputPath) { string PrintDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); // Must have write permissions to the path folder PdfWriter writer = new PdfWriter(outputPath); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf); // Title string Title = "撿貨單"; PdfFont Titlefont = PdfFontFactory.CreateFont(@"C:\windows\fonts\msjh.ttc,0", PdfEncodings.IDENTITY_H, false); int TitlefontSize = 20; Paragraph header = new Paragraph($"{Title}") .SetTextAlignment(TextAlignment.CENTER) .SetUnderline() .SetFont(Titlefont).SetFontSize(TitlefontSize); document.Add(header); PdfFont subItemfont = PdfFontFactory.CreateFont(@"C:\windows\fonts\msjh.ttc,0", PdfEncodings.IDENTITY_H, false); int subItemfontSize = 12; Table subItemTable = new Table(3, true); Cell cell13 = new Cell(1, 1) .SetTextAlignment(TextAlignment.RIGHT) .SetBorder(Border.NO_BORDER) .Add(new Paragraph($"列印日期: {PrintDate}") .SetFont(subItemfont).SetFontSize(subItemfontSize)); subItemTable.AddCell(cell13); document.Add(subItemTable); // Line separator LineSeparator ls = new LineSeparator(new SolidLine(4)); document.Add(ls); document.Add(DataList.ToPdfPTable()); document.Close(); }
private static Cell GetCell2() { Cell cell = new Cell(); Paragraph p1 = new Paragraph("My fantastic data"); cell.Add(p1); LineSeparator ls = new LineSeparator(new SolidLine()); cell.Add(ls); Paragraph p2 = new Paragraph("Other data"); cell.Add(p2); return(cell); }
public virtual void CreatePdf(String dest) { //Initialize PDF document PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); // Initialize document Document document = new Document(pdf); PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN); PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD); document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3)); StreamReader sr = File.OpenText(SRC); LineSeparator separator = new LineSeparator(new DottedLine(2f, 5f)); separator.SetMarginLeft(10); separator.SetMarginRight(10); bool chapter = false; Div div = new Div(); String line; while ((line = sr.ReadLine()) != null) { div = new Div().SetFont(font).SetFontSize(11).SetMarginBottom(18); div.Add(new Paragraph(line).SetFont(bold).SetFontSize(12).SetMarginBottom(0)); while ((line = sr.ReadLine()) != null) { div.Add(new Paragraph(line).SetMarginBottom(0).SetFirstLineIndent(36)); if (String.IsNullOrEmpty(line)) { if (chapter) { div.Add(separator); } document.Add(div); div = new Div(); chapter = true; break; } } } document.Add(div); //Close document document.Close(); }
public ActionResult MergeImages() { string imgFolder = @"C:\Users\Habiba\Desktop\APWDN\FileUpload\FileUpload\UploadedImages\"; string pdfFolder = @"C:\Users\Habiba\Desktop\APWDN\FileUpload\FileUpload\Generated PDFs\demo.pdf"; //Getting Images var imageFiles = Directory.GetFiles(imgFolder, "*.jpg"); List <string> imageList = new List <string>(); foreach (string image in imageFiles) { imageList.Add(image); } //Creating the pdf document PdfWriter writer = new PdfWriter(pdfFolder); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf); //Header Paragraph header = new Paragraph("DEMO").SetTextAlignment(TextAlignment.CENTER).SetFontSize(20); //New Line Paragraph newline = new Paragraph(new Text("\n")); //Adding Header & New Line document.Add(newline); document.Add(header); //Line Separator LineSeparator ls = new LineSeparator(new SolidLine()); document.Add(ls); //Adding the Images foreach (string i in imageList) { Image img = new Image(ImageDataFactory.Create(i)).SetTextAlignment(TextAlignment.CENTER); document.Add(img); } //Closing the document & returning content document.Close(); return(Content("PDF Generation Successful! <a href=" + "./Home/MergeImages" + ">Generate Another</a>")); }
private static Cell GetCell4() { Cell cell = new Cell(); Paragraph p1 = new Paragraph("My fantastic data"); p1.SetMarginBottom(20); cell.Add(p1); LineSeparator ls = new LineSeparator(new SolidLine()); cell.Add(ls); Paragraph p2 = new Paragraph("Other data"); p2.SetMarginTop(10); cell.Add(p2); return(cell); }
public void LineSeparator_Should_Separate_The_Order_Lines_Correctly_If_The_String_Passed_Is_In_The_Correct_Form() { //ARRANGE ProductQuantityTestData testData = GenerateProductQuantityTestData(); var teststring = testData.TestString; var LineSeparator = new LineSeparator(); //ACT var result = LineSeparator.Separate(teststring); //ASSERT Assert.AreEqual(testData.Names.Count, result.Length); for (int i = 0; i < testData.Names.Count; i++) { var subresult = result[i].Split(':'); Assert.AreEqual(testData.Names[i], subresult[0]); Assert.AreEqual(testData.Quantities[i], int.Parse(subresult[1])); } }
/// <summary> /// Creates the PDF file. /// </summary> /// <param name="html">the HTML file as a byte array</param> /// <param name="baseUri">the base URI</param> /// <param name="dest">the path to the resulting PDF</param> public void CreatePdf(byte[] html, String baseUri, String dest) { ConverterProperties properties = new ConverterProperties(); properties.SetBaseUri(baseUri); PdfWriter writer = new PdfWriter(dest); PdfDocument pdf = new PdfDocument(writer); pdf.SetDefaultPageSize(new PageSize(595, 14400)); Document document = HtmlConverter.ConvertToDocument(new MemoryStream(html), pdf, properties); EndPosition endPosition = new EndPosition(); LineSeparator separator = new LineSeparator(endPosition); document.Add(separator); document.GetRenderer().Close(); PdfPage page = pdf.GetPage(1); float y = endPosition.GetY() - 36; page.SetMediaBox(new Rectangle(0, y, 595, 14400 - y)); document.Close(); }
/* (non-Javadoc) * @see com.itextpdf.tool.xml.css.CssApplier#apply(com.itextpdf.text.Element, com.itextpdf.tool.xml.Tag) */ virtual public LineSeparator Apply(LineSeparator ls, Tag t, IPageSizeContainable psc) { float lineWidth = 1; IDictionary <String, String> css = t.CSS; if (css.ContainsKey(CSS.Property.HEIGHT)) { lineWidth = CssUtils.GetInstance().ParsePxInCmMmPcToPt(css[CSS.Property.HEIGHT]); } ls.LineWidth = lineWidth; BaseColor lineColor = BaseColor.BLACK; if (css.ContainsKey(CSS.Property.COLOR)) { lineColor = HtmlUtilities.DecodeColor(css[CSS.Property.COLOR]); } else if (css.ContainsKey(CSS.Property.BACKGROUND_COLOR)) { lineColor = HtmlUtilities.DecodeColor(css[CSS.Property.BACKGROUND_COLOR]); } ls.LineColor = lineColor; float percentage = 100; String widthStr; css.TryGetValue(CSS.Property.WIDTH, out widthStr); if (widthStr != null) { if (widthStr.Contains("%")) { percentage = float.Parse(widthStr.Replace("%", ""), CultureInfo.InvariantCulture); } else { percentage = (CssUtils.GetInstance().ParsePxInCmMmPcToPt(widthStr) / psc.PageSize.Width) * 100; } } ls.Percentage = percentage; ls.Offset = 9; return(ls); }
// Veja algumas referencias: // http://www.c-sharpcorner.com/UploadFile/f2e803/basic-pdf-creation-using-itextsharp-part-i/ // http://www.codeproject.com/Articles/686994/Create-Read-Advance-PDF-Report-using-iTextSharp-in // http://www.mikesdotnetting.com/article/88/itextsharp-drawing-shapes-and-graphics // http://stackoverflow.com/questions/4325151/adding-an-image-to-a-pdf-using-itextsharp-and-scale-it-properly // http://stackoverflow.com/questions/23598192/changing-font-size-in-itextsharp-table protected void Page_Load(object sender, EventArgs e) { // Limpa qualquer coisa já previamente renderizada! Response.ClearContent(); // Altera o tipo de documento Response.ContentType = "application/pdf"; // Novo PDF Document doc = new Document(PageSize.A4, 25, 25, 30, 30); // Create an instance to the PDF file by creating an instance of the PDF // Writer class using the document and the filestrem in the constructor. PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream); // comaça a gerar o PDF doc.Open(); // Add a simple and wellknown phrase to the document in a flow layout manner doc.Add(new Paragraph("Hello World!")); // desenha uma linha PdfContentByte cb = writer.DirectContent; cb.MoveTo(doc.PageSize.Width / 2, doc.PageSize.Height / 2); // posiciona no centro da página cb.LineTo(doc.PageSize.Width, doc.PageSize.Height); // Linha diagonal até o canto superior cb.Stroke(); // Efetiva o desenho // cria uma linha separadora LineSeparator line = new LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1); doc.Add(new Chunk(line)); // Adiciona uma imagem // Atemção para conflitos com o nome 'Image' (existe dentro do ASP.Net, Web.UI, e no iTextsharp) System.Drawing.Bitmap img = new System.Drawing.Bitmap(MapPath("../BoletoNet/Imagens/237.gif")); // Isso é apenas um teste, não estou validando a existencia do arquivo Image pic = iTextSharp.text.Image.GetInstance(img, System.Drawing.Imaging.ImageFormat.Jpeg); doc.Add(pic); Font fontTable = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); PdfPTable table = new PdfPTable(5); table.SpacingBefore = 45f; table.TotalWidth = 216f; table.DefaultCell.Phrase = new Phrase() { Font = fontTable }; for (int j = 0; j < 5; j++) table.AddCell(new Phrase("col" + j)); table.HeaderRows = 1; for (int i = 1; i < 15; i++) { for (int k = 0; k < 5; k++) { Phrase p = new Phrase("cell(" + i + "," + k + ")"); p.Font.Size = i; table.AddCell(p); } } doc.Add(table); // Close the document doc.Close(); // Close the writer instance writer.Close(); // Finaliza tudo! Response.End(); // Acho que estes são os elementos basicos que preciso para desenhar boletos 100% em PDF // O Teste2_BoletoHTML.aspx usa um conversor obsoleto de HTML/CSS para PDF }
private void TimestampPdf() { using (var pdfReader = new PdfReader(this.PdfProcessingPath)) { using (var pdfStamper = new PdfStamper(pdfReader, new FileStream(this.PdfPath, FileMode.Create))) { var parentField = PdfFormField.CreateTextField(pdfStamper.Writer, false, false, 0); parentField.FieldName = FieldName; var lineSeparator = new LineSeparator(); for (var pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++) { var pdfContentByte = pdfStamper.GetOverContent(pageNumber); TextField textField = null; if (this.Orientation == PdfOrientation.Portrait) { lineSeparator.DrawLine(pdfContentByte, PortraitFieldLeftX, PortraitFieldRightX, PortraitFieldUnderlineHeight); textField = new TextField(pdfStamper.Writer, new Rectangle(PortraitFieldLeftX, PortraitFieldLeftY, PortraitFieldRightX, PortraitFieldRightY), null); textField.Visibility = TextField.HIDDEN_BUT_PRINTABLE; } var childField = textField.GetTextField(); parentField.AddKid(childField); childField.PlaceInPage = pageNumber; } pdfStamper.AddAnnotation(parentField, 1); var pdfAction = PdfAction.JavaScript(LoadTimestampScript(), pdfStamper.Writer); pdfStamper.Writer.SetAdditionalAction(PdfWriter.WILL_PRINT, pdfAction); } } }