/// <summary>Transforms the given Rectangle into the image coordinate system which is [0,1]x[0,1] by default</summary> private Rectangle TransformRectIntoImageCoordinates(Rectangle rect, Matrix imageCtm) { Point[] points = TransformPoints(imageCtm, true, new Point(rect.GetLeft(), rect.GetBottom()), new Point(rect .GetLeft(), rect.GetTop()), new Point(rect.GetRight(), rect.GetBottom()), new Point(rect.GetRight(), rect .GetTop())); return(GetAsRectangle(points[0], points[1], points[2], points[3])); }
public virtual void HandleEvent(Event @event) { PdfDocumentEvent docEvent = (PdfDocumentEvent)@event; PdfDocument pdfDoc = docEvent.GetDocument(); PdfPage page = docEvent.GetPage(); int pageNumber = pdfDoc.GetPageNumber(page); iText.Kernel.Geom.Rectangle pageSize = page.GetPageSize(); PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc); double ancho_encabezado = vendedor_nombre.Length * 3.5; //Add header and footer pdfCanvas .BeginText() .SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD), 13) .MoveText(pageSize.GetWidth() / 2 - ancho_encabezado, pageSize.GetTop() - 60) .ShowText(vendedor_nombre) //.MoveText(60, -pageSize.GetTop() + 30) //.ShowText(pageNumber.ToString()) .EndText(); if (nombre_imagen != "") { iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(nombre_imagen)); img.Scale(0.50f, 0.50f); img.SetFixedPosition(0, pageSize.GetTop() - (img.GetImageHeight() / 2)); iText.Kernel.Geom.Rectangle area = page.GetPageSize(); new Canvas(pdfCanvas, pdfDoc, area) .Add(img); } }
/// <summary>Calculates intersection of the image and the render filter region in the coordinate system relative to the image. /// </summary> /// <returns> /// <code>null</code> if the image is fully covered and therefore is completely cleaned, /// <see cref="System.Collections.IList{E}"/> /// of /// <see cref="iText.Kernel.Geom.Rectangle"/> /// objects otherwise. /// </returns> private IList <Rectangle> GetImageAreasToBeCleaned(ImageRenderInfo image) { Rectangle imageRect = CalcImageRect(image); if (imageRect == null) { return(null); } IList <Rectangle> areasToBeCleaned = new List <Rectangle>(); foreach (Rectangle region in regions) { Rectangle intersectionRect = GetRectanglesIntersection(imageRect, region); if (intersectionRect != null) { if (imageRect.EqualsWithEpsilon(intersectionRect)) { // true if the image is completely covered return(null); } areasToBeCleaned.Add(TransformRectIntoImageCoordinates(intersectionRect, image.GetImageCtm())); } } return(areasToBeCleaned); }
/// <summary>Calculate the intersection of 2 Rectangles</summary> /// <param name="rect1">first Rectangle</param> /// <param name="rect2">second Rectangle</param> private Rectangle GetRectanglesIntersection(Rectangle rect1, Rectangle rect2) { float x1 = Math.Max(rect1.GetLeft(), rect2.GetLeft()); float y1 = Math.Max(rect1.GetBottom(), rect2.GetBottom()); float x2 = Math.Min(rect1.GetRight(), rect2.GetRight()); float y2 = Math.Min(rect1.GetTop(), rect2.GetTop()); return((x2 - x1 > 0 && y2 - y1 > 0) ? new Rectangle(x1, y1, x2 - x1, y2 - y1) : null); }
public void HandleEvent(Event @event) { PdfDocumentEvent docEvent = (PdfDocumentEvent)@event; PdfDocument pdfDoc = docEvent.GetDocument(); PdfPage page = docEvent.GetPage(); PdfCanvas canvas1 = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc); Rectangle rootArea = new Rectangle(35, 20, page.GetPageSize().GetWidth() - 70, 50); new Canvas(canvas1, pdfDoc, rootArea).Add(getTable(docEvent)); }
private void pdfAnalize(string src, int j) { iText.Kernel.Pdf.PdfDocument pdfDoc = new PdfDocument(new PdfReader(src)); int n = pdfDoc.GetNumberOfPages(); logger.Info($"********** Document:{src} --> Total Pages:{n} **********"); _textBoxListener.WriteLine($"INFO: ********** Document:{src} --> Total Pages:{n} **********"); logTextBox.SelectionStart = logTextBox.TextLength; logTextBox.ScrollToCaret(); //Rectangle rect = new Rectangle(0, 0,595, 842); iText.Kernel.Geom.Rectangle rect = new iText.Kernel.Geom.Rectangle(0, 0, 595, 50); TextRegionEventFilter regionFilter = new TextRegionEventFilter(rect); for (int i = 1; i <= n; i++) { totalPages++; PdfPage page = pdfDoc.GetPage(i); ITextExtractionStrategy strategy = new FilteredTextEventListener(new LocationTextExtractionStrategy(), regionFilter); string text = PdfTextExtractor.GetTextFromPage(page, strategy); //var result = Regex.Split(text, "\r\n|\r|\n"); if (text.Length > 0) { analizeText(i, text, j); } else { logger.Error($"Page: {i} --NO TEXT HAVE BEEN FOUND"); _textBoxListener.WriteLine($"ERROR: Page: {i} --NO TEXT HAVE BEEN FOUND"); logTextBox.SelectionStart = logTextBox.TextLength; logTextBox.ScrollToCaret(); dataGridView1.Rows[j].Cells[2].Value = "KO"; dataGridView1.Rows[j].Cells[2].Style.BackColor = Color.Red; if (dataGridView1.Rows[j].Cells[3].Value.ToString() == "" || dataGridView1.Rows[j].Cells[3].Value.ToString().Equals("")) { dataGridView1.Rows[j].Cells[3].Value = $" Check=> Page:{i}"; } else { dataGridView1.Rows[j].Cells[3].Value = dataGridView1.Rows[j].Cells[3].Value + " | " + $"Page:{i}"; } dataGridView1.Refresh(); } } logger.Info($"********** Document:{src} --> Extract Pages finished **********"); _textBoxListener.WriteLine($"INFO: ********** Document:{src} --> Extract Pages finished **********"); logTextBox.SelectionStart = logTextBox.TextLength; logTextBox.ScrollToCaret(); pdfDoc.Close(); }
/// <summary> /// Prompts the user with a requested save location for the to-be-generated PDF /// Iterates through all elements inside of relevant lists to create the required number of labels inside /// of the PDF document, separated by pages. /// </summary> /// <param name="lstArkSerials">List of strings, representative of the entered ARK serial numbers</param> /// <param name="lstInjectorSerials">List of strings, representative of the entered Injector serial numbers</param> public void saveLabels(List <string> lstArkSerials, List <string> lstInjectorSerials) { try { using (PdfWriter outWriter = new PdfWriter(fm.choseDirectory() + "/Smart-i-" + DateTime.UtcNow.ToString("MM-dd-yyyy") + ".pdf")) { bool multipleCopies = false; PdfDocument outPDF = new PdfDocument(outWriter); //Set to this size because an internet wizard said that it is 1 inch per 72 user units. //I have no idea where this number comes from but it makes something printable for 3"x3" iText.Kernel.Geom.Rectangle labelSize = new iText.Kernel.Geom.Rectangle(0, 0, 216, 216); iText.Layout.Document outDocument = new iText.Layout.Document(outPDF, new PageSize(labelSize)); if (Settings.Default.copies > 1) { multipleCopies = true; } for (int i = 0; i < lstArkSerials.Count(); i++) { for (int j = 1; j <= Settings.Default.copies; j++) { createLabel(outDocument, outPDF, lstArkSerials.ElementAt(i), lstInjectorSerials.ElementAt(i), multipleCopies, j, Settings.Default.copies); } } outDocument.Close(); outPDF.Close(); outWriter.Close(); MessageBox.Show("Your file was successfully exported in your chosen directory as 'Smart-i-" + DateTime.UtcNow.ToString("MM-dd-yyyy") + ".pdf'", "Success!", MessageBoxButtons.OK); } } catch (System.IO.IOException) { MessageBox.Show("An unexcected error occured when trying to save the file in that location. Is there already a file" + " with that name open and in use? Does the selected directory exist? Do you have permissions to save inside of it?" + "\nPlease try again.", "Unexected Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (System.InvalidOperationException) { MessageBox.Show("Export was cancelled. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void AddHeader(Document doc, PdfDocument pdfDoc) { Paragraph header = new Paragraph("Example of PDF report by Ricardo Gaefke") .SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD)) .SetFontColor(ColorConstants.GRAY) .SetFontSize(8) .SetBorderBottom(new SolidBorder(ColorConstants.LIGHT_GRAY, 1)) .SetWidth(539) ; for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { iText.Kernel.Geom.Rectangle pageSize = pdfDoc.GetPage(i).GetPageSize(); float x = pageSize.GetWidth() / 2; float y = pageSize.GetTop() - 30; doc.ShowTextAligned(header, x, y, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0); } }
private void AddFooter(Document doc, PdfDocument pdfDoc, string text, string guid, string language) { Paragraph footer = new Paragraph($"{text} ") .SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD)) .SetFontSize(8) .SetBorderTop(new SolidBorder(ColorConstants.LIGHT_GRAY, 1)) .SetWidth(539) ; Link link = new Link($"https://pdf.ricardogaefke.com/check/{guid}/{language}", PdfAction.CreateURI($"https://pdf.ricardogaefke.com/check/{guid}/{language}")); footer.Add(link); for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { iText.Kernel.Geom.Rectangle pageSize = pdfDoc.GetPage(i).GetPageSize(); float x = pageSize.GetWidth() / 2; float y = pageSize.GetBottom() + 25; doc.ShowTextAligned(footer, x, y, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0); } }
public Esito PopolaPannelloNotaSpese(DatiAgenda eventoSelezionato, FiguraProfessionale figuraProfessionaleSelezionata) { Esito esito = new Esito(); try { if (eventoSelezionato != null && eventoSelezionato.LavorazioneCorrente != null) { #region LEGGO I PARAMETRI DI VS Config cfAppo = Config_BLL.Instance.getConfig(ref esito, "PARTITA_IVA"); string pIvaVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "DENOMINAZIONE"); string denominazioneVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "TOPONIMO"); string toponimoVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "INDIRIZZO"); string indirizzoVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "CIVICO"); string civicoVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "CAP"); string capVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "CITTA"); string cittaVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "PROVINCIA"); string provinciaVs = cfAppo.valore; cfAppo = Config_BLL.Instance.getConfig(ref esito, "EMAIL"); string emailVs = cfAppo.valore; #endregion List <DatiPianoEsternoLavorazione> listaDatiPianoEsternoLavorazione = eventoSelezionato.LavorazioneCorrente.ListaDatiPianoEsternoLavorazione; if (listaDatiPianoEsternoLavorazione != null) { string nomeFile = "NotaSpese.pdf"; string pathNotaSpese = ConfigurationManager.AppSettings["PATH_DOCUMENTI_PROTOCOLLO"] + nomeFile; string mapPathNotaSpese = MapPath(ConfigurationManager.AppSettings["PATH_DOCUMENTI_PROTOCOLLO"]) + nomeFile; //string prefissoUrl = Request.Url.Scheme + "://" + Request.Url.Authority; iText.IO.Image.ImageData imageData = iText.IO.Image.ImageDataFactory.Create(MapPath("~/Images/logoVSP_trim.png")); PdfWriter wr = new PdfWriter(mapPathNotaSpese); PdfDocument doc = new PdfDocument(wr); doc.SetDefaultPageSize(iText.Kernel.Geom.PageSize.A4.Rotate()); Document document = new Document(doc); document.SetMargins(50, 30, 50, 30); // COLORE BLU VIDEOSYSTEM iText.Kernel.Colors.Color coloreIntestazioni = new iText.Kernel.Colors.DeviceRgb(33, 150, 243); Paragraph pIntestazioneNotaSpese = new Paragraph("Nota Spese di: " + figuraProfessionaleSelezionata.Nome + " " + figuraProfessionaleSelezionata.Cognome); pIntestazioneNotaSpese.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); pIntestazioneNotaSpese.SetFontSize(20); pIntestazioneNotaSpese.SetBold(); document.Add(pIntestazioneNotaSpese); // AGGIUNGO TABLE PER LAYOUT INTESTAZIONE iText.Layout.Element.Table tbIntestazione = new iText.Layout.Element.Table(new float[] { 1, 9 }).UseAllAvailableWidth().SetBorder(iText.Layout.Borders.Border.NO_BORDER); iText.Layout.Element.Image image = new iText.Layout.Element.Image(imageData).ScaleAbsolute(90, 80).SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.CENTER); Cell cellaImmagine = new Cell().SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.MIDDLE).SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.CENTER); cellaImmagine.Add(image); tbIntestazione.AddCell(cellaImmagine); iText.Layout.Element.Table tbIntestazioneDx = new iText.Layout.Element.Table(new float[] { 2, 3, 2, 3 }).UseAllAvailableWidth().SetBorder(iText.Layout.Borders.Border.NO_BORDER); Anag_Clienti_Fornitori cliente = Anag_Clienti_Fornitori_BLL.Instance.getAziendaById(eventoSelezionato.id_cliente, ref esito); Paragraph pTitolo = new Paragraph("Cliente").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); Paragraph pValore = new Paragraph(cliente.RagioneSociale.Trim()).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE); tbIntestazioneDx.AddCell(pValore).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Referente").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); string nomeReferente = ""; if (eventoSelezionato.LavorazioneCorrente.IdReferente != null) { Anag_Referente_Clienti_Fornitori referente = Anag_Referente_Clienti_Fornitori_BLL.Instance.getReferenteById(ref esito, Convert.ToInt32(eventoSelezionato.LavorazioneCorrente.IdReferente.Value)); nomeReferente = referente.Nome + " " + referente.Cognome; } pValore = new Paragraph(nomeReferente).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pValore).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Produzione").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pValore = new Paragraph(eventoSelezionato.produzione).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pValore).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Capotecnico").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); string nomeCapotecnico = ""; if (eventoSelezionato.LavorazioneCorrente.IdCapoTecnico != null) { Anag_Collaboratori coll = Anag_Collaboratori_BLL.Instance.getCollaboratoreById(eventoSelezionato.LavorazioneCorrente.IdCapoTecnico.Value, ref esito); nomeCapotecnico = coll.Nome + " " + coll.Cognome; } pValore = new Paragraph(nomeCapotecnico).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pValore).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Lavorazione").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(eventoSelezionato.lavorazione).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Data Inizio").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(eventoSelezionato.data_inizio_impegno.ToShortDateString()).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Luogo").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(eventoSelezionato.luogo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Data Lavoraz.").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(eventoSelezionato.data_inizio_lavorazione.ToShortDateString()).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Indirizzo").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(eventoSelezionato.indirizzo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); pTitolo = new Paragraph("Cod.Lavor.").SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(pTitolo).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazioneDx.AddCell(eventoSelezionato.codice_lavoro).SetBorder(iText.Layout.Borders.Border.NO_BORDER); tbIntestazione.AddCell(tbIntestazioneDx).SetBorder(iText.Layout.Borders.Border.NO_BORDER); document.Add(tbIntestazione); Paragraph pSpazio = new Paragraph(" "); document.Add(pSpazio); Paragraph pLuogoData = new Paragraph(cittaVs + ", " + DateTime.Today.ToLongDateString()); pLuogoData.SetFontSize(8); document.Add(pLuogoData); document.Add(pSpazio); // INTESTAZIONE GRIGLIA iText.Layout.Element.Table table = new iText.Layout.Element.Table(new float[] { 90, 70, 70, 70, 70, 70, 70, 70, 200 }).SetWidth(780); Border bordoDoppio = new DoubleBorder(1); Cell cella = new Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER); table.AddHeaderCell(cella); Paragraph intestazioneMain = new Paragraph("Tipologia di pagamento").SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); cella = new Cell(1, 3).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); cella.SetBorderLeft(bordoDoppio); cella.Add(intestazioneMain); table.AddHeaderCell(cella); intestazioneMain = new Paragraph("Costi in Euro").SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); cella = new Cell(1, 5).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); cella.SetBorderLeft(bordoDoppio); cella.Add(intestazioneMain); table.AddHeaderCell(cella); Paragraph intestazione = new Paragraph("Data").SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); table.AddHeaderCell(intestazione).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Sofid").SetFontSize(10).SetBold().SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); cella = new Cell().SetBorderLeft(bordoDoppio); cella.Add(intestazione); table.AddHeaderCell(cella).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Carta").SetFontSize(10).SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); table.AddHeaderCell(intestazione).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Contanti").SetFontSize(10).SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); table.AddHeaderCell(intestazione).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Carburante").SetFontSize(10).SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); cella = new Cell().SetBorderLeft(bordoDoppio); cella.Add(intestazione); table.AddHeaderCell(cella).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Albergo").SetFontSize(10).SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); table.AddHeaderCell(intestazione).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Trasporti").SetFontSize(10).SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); table.AddHeaderCell(intestazione).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Pasti").SetFontSize(10).SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); table.AddHeaderCell(intestazione).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); intestazione = new Paragraph("Varie").SetFontSize(10).SetBold().SetBackgroundColor(coloreIntestazioni, 0.7f); table.AddHeaderCell(intestazione).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); // CELLE VUOTE for (int i = 0; i < 12; i++) { table.AddCell(new Cell().SetHeight(15)); cella = new Cell().SetBorderLeft(bordoDoppio); table.AddCell(cella); table.AddCell(" "); table.AddCell(" "); cella = new Cell().SetBorderLeft(bordoDoppio); table.AddCell(cella); table.AddCell(" "); table.AddCell(" "); table.AddCell(" "); table.AddCell(" "); } document.Add(table); Paragraph pFirma = new Paragraph("in fede"); pFirma.SetFontSize(9); pFirma.SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT); pFirma.SetMarginRight(90); pFirma.SetMarginTop(13); document.Add(pFirma); iText.Kernel.Geom.Rectangle pageSize = doc.GetPage(1).GetPageSize(); int n = doc.GetNumberOfPages(); // AGGIUNGO CONTEGGIO PAGINE E FOOTER PER OGNI PAGINA for (int i = 1; i <= n; i++) { //AGGIUNGO NUM.PAGINA document.ShowTextAligned(new Paragraph("pagina " + i.ToString() + " di " + n.ToString()).SetFontSize(7), pageSize.GetWidth() - 60, pageSize.GetHeight() - 20, i, iText.Layout.Properties.TextAlignment.CENTER, iText.Layout.Properties.VerticalAlignment.TOP, 0); //AGGIUNGO FOOTER document.ShowTextAligned(new Paragraph(denominazioneVs + " P.IVA " + pIvaVs + Environment.NewLine + "Sede legale: " + toponimoVs + " " + indirizzoVs + " " + civicoVs + " - " + capVs + " " + cittaVs + " " + provinciaVs + " e-mail: " + emailVs).SetFontSize(7).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER), pageSize.GetWidth() / 2, 30, i, iText.Layout.Properties.TextAlignment.CENTER, iText.Layout.Properties.VerticalAlignment.TOP, 0); } //document.Flush(); document.Close(); wr.Close(); framePdfNotaSpese.Attributes.Remove("src"); framePdfNotaSpese.Attributes.Add("src", pathNotaSpese.Replace("~", "")); DivFramePdfNotaSpese.Visible = true; framePdfNotaSpese.Visible = true; ScriptManager.RegisterStartupScript(Page, typeof(Page), "aggiornaFrame", script: "javascript: document.getElementById('" + framePdfNotaSpese.ClientID + "').contentDocument.location.reload(true);", addScriptTags: true); btnStampaNotaSpese.Attributes.Add("onclick", "window.open('" + pathNotaSpese.Replace("~", "") + "');"); } } } catch (Exception ex) { esito.Codice = Esito.ESITO_KO_ERRORE_GENERICO; esito.Descrizione = "PopolaPannelloNotaSpese(DatiAgenda eventoSelezionato, FiguraProfessionale figuraProfessionaleSelezionata) " + ex.Message + Environment.NewLine + ex.StackTrace; } return(esito); }
protected override void DrawBars(PdfCanvas canvas, PdfPage page) { int columnCount = _data.Columns.Count; float totalColumnWidth = (_axisWidth / columnCount); float barMargin = (totalColumnWidth - _barWidth) / 2; float x = _originX + barMargin; if (_svgRender) { foreach (Column column in _data.Columns) { float y = _originY; foreach (Value value in column.Values) { if (_barDrawBorder) { _svgWriter.Rectangle(x, y, _barWidth, value.Data * _yScale, GetColorFromiTextColour(value.Legend.Colour), GetColorFromiTextColour(_barBorderColour), _barBorderWidth); } else { System.Drawing.Color temp = new System.Drawing.Color(); _svgWriter.Rectangle(x, y, _barWidth, value.Data * _yScale, GetColorFromiTextColour(value.Legend.Colour), temp, 0.0f); } y += value.Data * _yScale; } x += totalColumnWidth; } } else { foreach (Column column in _data.Columns) { float y = _originY; foreach (Value value in column.Values) { iText.Kernel.Geom.Rectangle rectangle = new iText.Kernel.Geom.Rectangle(x, y, _barWidth, value.Data * _yScale); float[] rgb = value.Legend.Colour.GetColorValue(); Debug.WriteLine("Legend: " + value.Legend.Label + " r:" + rgb[0].ToString("0.00") + " g:" + rgb[1].ToString("0.00") + " b:" + rgb[2].ToString("0.00")); canvas.SetFillColor(value.Legend.Colour); canvas.Rectangle(rectangle); canvas.Fill(); if (_barDrawBorder) { rectangle = new iText.Kernel.Geom.Rectangle(x, y + _barBorderWidth / 2, _barWidth, value.Data * _yScale - _barBorderWidth / 2); canvas.SetStrokeColor(_barBorderColour); canvas.SetLineWidth(_barBorderWidth); canvas.Rectangle(rectangle); canvas.Stroke(); } y += value.Data * _yScale; } x += totalColumnWidth; } } }
public ActionResult buildPDF(List <InformeResponse> lista, string nombreAsada) { MemoryStream ms = new MemoryStream(); PdfWriter pw = new PdfWriter(ms); PdfDocument pdfDocument = new PdfDocument(pw); Document doc = new Document(pdfDocument, PageSize.LETTER, false); doc.Add(new Paragraph("Reporte " + nombreAsada).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER).SetFontColor(new DeviceRgb(4, 124, 188))); foreach (InformeResponse item in lista) { Preguntas preguntasObj = TipoFormulario(item.tipo); doc.Add(new Paragraph(item.acueducto).SetFontSize(15).SetBold()); doc.Add(new Paragraph("Fecha: " + item.fecha).SetFontSize(12)); doc.Add(new Paragraph("Encargado: " + item.encargado).SetFontSize(12).SetPaddingBottom(2)); doc.Add(new Paragraph("Respuestas ").SetFontSize(12).SetUnderline()); var infra = JsonConvert.DeserializeObject <Dictionary <string, string> >(item.infraestructura); foreach (var kv in infra) { if (kv.Key == "P1") { doc.Add(new Paragraph(preguntasObj.p1 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P2") { doc.Add(new Paragraph(preguntasObj.p2 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P3") { doc.Add(new Paragraph(preguntasObj.p3 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P4") { doc.Add(new Paragraph(preguntasObj.p4 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P5") { doc.Add(new Paragraph(preguntasObj.p5 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P6") { doc.Add(new Paragraph(preguntasObj.p6 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P7") { doc.Add(new Paragraph(preguntasObj.p7 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P8") { doc.Add(new Paragraph(preguntasObj.p8 + ": " + kv.Value).SetFontSize(10)); } else if (kv.Key == "P9") { doc.Add(new Paragraph(preguntasObj.p9 + ": " + kv.Value).SetFontSize(10)); } } doc.Add(new Paragraph("Comentarios: " + item.comentarios).SetFontSize(12)); doc.Add(new Paragraph("Tipo de formulario: " + preguntasObj.tipo).SetFontSize(12)); Cell cell = new Cell(); cell.Add(new Paragraph("Riesgo " + item.riesgo).SetBorder(new SolidBorder(colorRiesgo(item.riesgo), 1)).SetBackgroundColor(colorRiesgo(item.riesgo)).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).SetFontSize(14).SetBold()); doc.Add(cell); WebClient webClient = new WebClient(); byte[] data = webClient.DownloadData(item.imagen); ImageData imageData = ImageDataFactory.Create(data); Image image = new Image(imageData); var s = 0.4; float fwi = (float)s; float fhei = (float)s; doc.Add(image.Scale(fwi, fhei).SetHorizontalAlignment(HorizontalAlignment.CENTER).SetMarginBottom(15).SetMarginTop(15)); } //imagen del logo de sersa var s2 = 0.08; float fwi2 = (float)s2; float fhei2 = (float)s2; WebClient webClient2 = new WebClient(); byte[] data2 = webClient2.DownloadData(logoletra); ImageData imageData2 = ImageDataFactory.Create(data2); Image image2 = new Image(imageData2); Paragraph header = new Paragraph(""); header.Add(image2.Scale(fwi2, fhei2).SetMarginBottom(15)); //imagen del logo de TEC var s3 = 0.4; float fwi3 = (float)s3; float fhei3 = (float)s3; WebClient webClient3 = new WebClient(); byte[] data3 = webClient3.DownloadData(logotec); ImageData imageData3 = ImageDataFactory.Create(data3); Image image3 = new Image(imageData3); Paragraph header2 = new Paragraph(""); header2.Add(image3.Scale(fwi3, fhei3)).SetMarginBottom(10); for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) { Rectangle pageSize = pdfDocument.GetPage(i).GetPageSize(); float x1 = 20; float y1 = pageSize.GetTop() - 55; float x2 = pageSize.GetRight() - 30; float y2 = pageSize.GetTop() - 40; doc.ShowTextAligned(header, x1, y1, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0); doc.ShowTextAligned(header2, x2, y2, i, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0); } doc.Close(); byte[] bytesStream = ms.ToArray(); ms = new MemoryStream(); ms.Write(bytesStream, 0, bytesStream.Length); ms.Position = 0; return(new FileStreamResult(ms, "application/pdf")); }
public override void EventOccurred(IEventData data, EventType type) { if (!type.Equals(EventType.RENDER_TEXT)) { return; } TextRenderInfo renderInfo = (TextRenderInfo)data; float counter = _increaseCounter(); var font = renderInfo.GetFont().GetFontProgram(); var originalFontName = font.ToString(); var fontRegex = Regex.Match(originalFontName, @"(?<=\+)[a-zA-Z\s]+"); string fontName = fontRegex.Success ? fontRegex.Value : originalFontName; var fontStyle = GetFontStyle(font.GetFontNames()); float curFontSize = renderInfo.GetFontSize(); float key = counter; IList <TextRenderInfo> text = renderInfo.GetCharacterRenderInfos(); foreach (TextRenderInfo character in text) { key += 0.001f; var textRenderMode = character.GetTextRenderMode(); var opacity = character.GetGraphicsState().GetFillOpacity(); //if (textRenderMode != 0 || opacity != 1) //{ //} string letter = character.GetText(); Color color; var fillColor = character.GetFillColor(); var colors = fillColor.GetColorValue(); if (colors.Length == 1) { color = Color.FromArgb((int)(255 * (1 - colors[0])), Color.Black); } else if (colors.Length == 3) { color = Color.FromArgb((int)(255 * colors[0]), (int)(255 * colors[1]), (int)(255 * colors[2])); } else if (colors.Length == 4) { color = Color.FromArgb((int)(255 * colors[0]), (int)(255 * colors[1]), (int)(255 * colors[2]), (int)(255 * colors[3])); } else { color = Color.Black; } //if(letter == "A") //{ //} if (string.IsNullOrWhiteSpace(letter)) { continue; } //Get the bounding box for the chunk of text var bottomLeft = character.GetDescentLine().GetStartPoint(); var topRight = character.GetAscentLine().GetEndPoint(); //Create a rectangle from it var rect = new iText.Kernel.Geom.Rectangle( bottomLeft.Get(Vector.I1), topRight.Get(Vector.I2), topRight.Get(Vector.I1), topRight.Get(Vector.I2) ); var currentChunk = new TextChunk() { Text = letter, Rect = rect, FontFamily = fontName, FontSize = (int)curFontSize, FontStyle = fontStyle, Color = color, SpaceWidth = character.GetSingleSpaceWidth() / 2f }; _chunkDictionary.Add(key, currentChunk); } base.EventOccurred(data, type); }
/// <summary>Convert a Rectangle object into 4 Points</summary> /// <param name="rect">input Rectangle</param> private Point[] GetRectangleVertices(Rectangle rect) { Point[] points = new Point[] { new Point(rect.GetLeft(), rect.GetBottom()), new Point(rect.GetRight(), rect .GetBottom()), new Point(rect.GetRight(), rect.GetTop()), new Point(rect.GetLeft(), rect.GetTop()) }; return(points); }
/// <summary> /// Watermarks a PDF file. /// </summary> /// <paramref name="fileName"/> private void WatermarkPdf(string fileName) { var watermarkText = _operation.WatermarkText; var sourceFile = $"{_operation.SourcePath}\\{fileName}"; var destinationPath = $"{_operation.DestinationPath}\\{PathWatermarked}"; var destinationFile = $"{destinationPath}\\{fileName}"; ValidatePath(destinationPath); const float watermarkTrimmingRectangleWidth = 600; const float watermarkTrimmingRectangleHeight = 600; const float formWidth = 300; const float formHeight = 300; const float formXOffset = 0; const float formYOffset = 0; const float xTranslation = 50; const float yTranslation = 25; const double rotationInRads = Math.PI / 3; try { FontCache.ClearSavedFonts(); } catch (Exception exception) { Log.Error(exception.Message); } var font = PdfFontFactory.CreateFont(StandardFonts.COURIER); const float fontSize = 119; using var reader = new PdfReader(new MemoryStream(File.ReadAllBytes(sourceFile))); using var pdfDoc = new PdfDocument(reader, new PdfWriter(destinationFile)); var numberOfPages = pdfDoc.GetNumberOfPages(); PdfPage page = null; for (var i = 1; i <= numberOfPages; i++) { page = pdfDoc.GetPage(i); var ps = page.GetPageSize(); //Center the annotation var bottomLeftX = ps.GetWidth() / 2 - watermarkTrimmingRectangleWidth / 2; var bottomLeftY = ps.GetHeight() / 2 - watermarkTrimmingRectangleHeight / 2; var watermarkTrimmingRectangle = new Rectangle(bottomLeftX, bottomLeftY, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight); var watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle); //Apply linear algebra rotation math //Create identity matrix var transform = new AffineTransform(); //No-args constructor creates the identity transform //Apply translation transform.Translate(xTranslation, yTranslation); //Apply rotation transform.Rotate(rotationInRads); var fixedPrint = new PdfFixedPrint(); watermark.SetFixedPrint(fixedPrint); //Create appearance var formRectangle = new Rectangle(formXOffset, formYOffset, formWidth, formHeight); //Observation: font XObject will be resized to fit inside the watermark rectangle var form = new PdfFormXObject(formRectangle); var gs1 = new PdfExtGState().SetFillOpacity(0.6f); var canvas = new PdfCanvas(form, pdfDoc); var transformValues = new float[6]; transform.GetMatrix(transformValues); canvas.SaveState() .BeginText().SetColor(ColorConstants.GRAY, true).SetExtGState(gs1) .SetTextMatrix(transformValues[0], transformValues[1], transformValues[2], transformValues[3], transformValues[4], transformValues[5]) .SetFontAndSize(font, fontSize) .ShowText(watermarkText) .EndText() .RestoreState(); canvas.Release(); watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject())); watermark.SetFlags(PdfAnnotation.PRINT); page.AddAnnotation(watermark); } page?.Flush(); pdfDoc.Close(); }
public void printLabels(List <string> lstArkSerials, List <string> lstInjectorSerials) { try { using (var stream = new MemoryStream()) { using (PdfWriter outWriter = new PdfWriter(stream)) { bool multipleCopies = false; PdfDocument outPDF = new PdfDocument(outWriter); //Set to this size because an internet wizard said that it is 1 inch per 72 user units. //I have no idea where this number comes from but it makes something printable for 3"x3" iText.Kernel.Geom.Rectangle labelSize = new iText.Kernel.Geom.Rectangle(0, 0, 216, 216); iText.Layout.Document outDocument = new iText.Layout.Document(outPDF, new PageSize(labelSize)); if (Settings.Default.copies > 1) { multipleCopies = true; } for (int i = 0; i < lstArkSerials.Count(); i++) { for (int j = 1; j <= Settings.Default.copies; j++) { createLabel(outDocument, outPDF, lstArkSerials.ElementAt(i), lstInjectorSerials.ElementAt(i), multipleCopies, j, Settings.Default.copies); } } outDocument.Close(); outPDF.Close(); outWriter.Close(); byte[] bytes = stream.ToArray(); using (var outStream = new MemoryStream(bytes)) { using (var document = PdfiumViewer.PdfDocument.Load(outStream)) { using (var printDocument = document.CreatePrintDocument()) { using (PrintDialog dialog = new PrintDialog()) { printDocument.PrinterSettings.PrintFileName = "Smart-i-" + DateTime.UtcNow.ToString("MM-dd-yyyy") + ".pdf"; printDocument.DocumentName = "Smart-i-" + DateTime.UtcNow.ToString("MM-dd-yyyy") + ".pdf"; printDocument.PrinterSettings.PrintFileName = "file.pdf"; printDocument.PrintController = new StandardPrintController(); printDocument.PrinterSettings.MinimumPage = 1; printDocument.PrinterSettings.FromPage = 1; printDocument.PrinterSettings.ToPage = document.PageCount; printDocument.DefaultPageSettings.PaperSize = new PaperSize("3 x 3 inches", 300, 300); dialog.Document = printDocument; dialog.AllowPrintToFile = true; dialog.AllowSomePages = true; if (dialog.ShowDialog() == DialogResult.OK) { dialog.Document.Print(); } } } } } } } } catch (System.InvalidOperationException) { MessageBox.Show("Printer job was cancelled. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private static void CreateLink(object document, Link.LinkControl control, Paragraph header, bool border) { for (int k = 0; k < control.Controls.Count; k++) { if (control.Controls[k].GetType() == typeof(LinkLabel)) { Style style = new Style(); LinkLabel label = control.Controls[k] as LinkLabel; iText.Kernel.Geom.Rectangle rect = new iText.Kernel.Geom.Rectangle(0, 0); PdfLinkAnnotation annotation = new PdfLinkAnnotation(rect); PdfAction action = PdfAction.CreateURI(label.Links[0].LinkData.ToString()); annotation.SetAction(action); annotation.SetContents(label.ContextMenuStrip.Text); iText.Layout.Element.Link link = new iText.Layout.Element.Link(label.Text, annotation); style.SetFont(PdfFontFactory.CreateFont("C:\\Windows\\Fonts\\times.ttf", "Cp1251", true)); style.SetFontSize(label.Font.Size); if (label.Font.Bold) { style.SetBold(); } if (label.Font.Italic) { style.SetItalic(); } style.SetUnderline(); if (label.Font.Strikeout) { style.SetLineThrough(); } style.SetFontColor(ColorConstants.BLUE); header.Add(link.AddStyle(style)); #region Анотация, которую я так и не смог сделать /* * // Creating a PdfTextMarkupAnnotation object * rect = new Rectangle(35, 785, 0, 0); * float[] floatArray = new float[] { 35, 785, 45, 785, 35, 795, 45, 795 }; * PdfAnnotation Annotation = PdfTextMarkupAnnotation.CreateUnderline(rect, floatArray); * * // Setting color to the annotation * Annotation.SetColor(ColorConstants.BLUE); * * // Setting title to the annotation * Annotation.SetTitle(new PdfString(label.ContextMenuStrip.Text)); * * // Setting contents to the annotation * Annotation.SetContents(" "); * * // Creating a new Pdfpage * PdfPage pdfPage = pdf.AddNewPage(); * * // Adding annotation to a page in a PDF * pdfPage.AddAnnotation(Annotation); */ #endregion } else { ImageText.ImageTextControl picture = (control.Controls[k] as ImageText.ImageTextControl); CreateImage(document, picture, true, ref header, border, k + 1 == control.Controls.Count); } } }
protected override void DrawBars(PdfCanvas canvas, PdfPage page) { int columnCount = _data.Columns.Count; int barCount = _data.Legends.Count; float x = _originX + _barMargin; float y = _originY; if (_svgRender) { foreach (Column column in _data.Columns) { foreach (Value value in column.Values) { if (_barDrawBorder) { _svgWriter.Rectangle(x, y, _barWidth, value.Data * _yScale, GetColorFromiTextColour(value.Legend.Colour), GetColorFromiTextColour(_barBorderColour), _barBorderWidth); } else { System.Drawing.Color temp = new System.Drawing.Color(); _svgWriter.Rectangle(x, y, _barWidth, value.Data * _yScale, GetColorFromiTextColour(value.Legend.Colour), temp, 0.0f); } String text = value.Data.ToString("0.0"); if (_data.FormatPercent) { text = text + "%"; } float textWidth = _font.GetWidth(text, _barValueFontSize); float textHeight = _font.GetAscent(text, _barValueFontSize) + _font.GetDescent(text, _barValueFontSize); float textX = x + (_barWidth / 2); if (_barDrawValueAboveTop) { float textY = _originY + value.Data * _yScale + _barValueMargin; _svgWriter.Text(textX, textY, text, GetColorFromiTextColour(_barValueFontColour), "middle", -0.0f, _barValueFontSize); } if (_barDrawValueBelowTop) { float textY = _originY + value.Data * _yScale - _barValueMargin - textHeight; _svgWriter.Text(textX, textY, text, GetColorFromiTextColour(_barValueFontColour), "middle", -0.0f, _barValueFontSize); } if (_barDrawValueCenter) { float textY = _originY + (value.Data * _yScale) / 2 - textHeight / 2; _svgWriter.Text(textX, textY, text, GetColorFromiTextColour(_barValueFontColour), "middle", -0.0f, _barValueFontSize); } x += _barWidth; } x += _barMargin; } } else { foreach (Column column in _data.Columns) { foreach (Value value in column.Values) { iText.Kernel.Geom.Rectangle rectangle = new iText.Kernel.Geom.Rectangle(x, y, _barWidth, value.Data * _yScale); canvas.SetFillColor(value.Legend.Colour); canvas.Rectangle(rectangle); canvas.Fill(); if (_barDrawBorder) { rectangle = new iText.Kernel.Geom.Rectangle(x, y + _barBorderWidth / 2, _barWidth, value.Data * _yScale - _barBorderWidth / 2); canvas.SetStrokeColor(_barBorderColour); canvas.SetLineWidth(_barBorderWidth); canvas.Rectangle(rectangle); canvas.Stroke(); } String text = value.Data.ToString("0.0"); if (_data.FormatPercent) { text = text + "%"; } float textWidth = _font.GetWidth(text, _barValueFontSize); float textHeight = _font.GetAscent(text, _barValueFontSize) + _font.GetDescent(text, _barValueFontSize); float textX = x + (_barWidth / 2) - (textWidth / 2); if (_barDrawValueAboveTop) { float textY = _originY + value.Data * _yScale + _barValueMargin; canvas.BeginText() .SetFontAndSize(_font, _barValueFontSize) .MoveText(textX, textY) .SetColor(_barValueFontColour, true) .ShowText(text) .EndText(); } if (_barDrawValueBelowTop) { float textY = _originY + value.Data * _yScale - _barValueMargin - textHeight; canvas.BeginText() .SetFontAndSize(_font, _barValueFontSize) .MoveText(textX, textY) .SetColor(_barValueFontColour, true) .ShowText(text) .EndText(); } if (_barDrawValueCenter) { float textY = _originY + (value.Data * _yScale) / 2 - textHeight / 2; canvas.BeginText() .SetFontAndSize(_font, _barValueFontSize) .MoveText(textX, textY) .SetColor(_barValueFontColour, true) .ShowText(text) .EndText(); } x += _barWidth; } x += _barMargin; } } }