/* * * Metoda odpowiedzialna. za tworzenie paragonu. */ public void Bill() { var pokUserInfo = this._dataService.GetPokInformation(LoginForm.sendtext); orderNr = this._dataService.GetTransactionId(); string path = Directory.GetCurrentDirectory(); string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string now2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); iTextSharp.text.Font x = FontFactory.GetFont("HELVETICA_BOLD", 17); System.Windows.Shapes.Rectangle ee = new System.Windows.Shapes.Rectangle(); var pdfDoc = new Document(new iTextSharp.text.Rectangle(200f, 390f)); SaveFileDialog sfd = new SaveFileDialog(); sfd.FileName = desktop + "\\PAR_NR_" + orderNr + ".pdf"; sfd.Filter = "Pdf File |*.pdf"; if (sfd.ShowDialog() == DialogResult.OK && sfd.FileName != "") { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(sfd.FileName, FileMode.OpenOrCreate)); pdfDoc.Open(); pdfDoc.Add(new Paragraph(" Smart Sell", x)); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path + "\\logo.png"); image.ScalePercent(22f); image.SetAbsolutePosition(25, 315); pdfDoc.Add(image); PdfContentByte cb = writer.DirectContent; cb.SaveState(); cb.SetColorFill(BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 9f); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Zarząd Transportu Miejskiego", 105, 311, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "ul. Dembowskiego 17", 105, 300, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "36-100 Kolbuszowa", 101, 288, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "PARAGON NIEFISKALNY", 100, 20, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "ODBIORCA :", 8, 218, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "ID KLIENTA :", 8, 208, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "NR TRANSAKCJI :", 8, 198, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, clientName, 88, 218, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Ilość :" + Quantity, 8, 145, 0); if (Convert.ToInt64(CLIENTID) < 10) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "00" + CLIENTID, 88, 208, 0); } else if (Convert.ToInt64(CLIENTID) >= 10) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "0" + CLIENTID, 88, 208, 0); } if (Convert.ToInt64(orderNr) < 10) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "00" + orderNr, 88, 198, 0); } else if (Convert.ToInt64(orderNr) >= 10) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "0" + orderNr, 88, 198, 0); } cb.EndText(); cb.RestoreState(); PdfContentByte cb2 = writer.DirectContent; cb2.SaveState(); cb2.SetColorFill(BaseColor.BLACK); cb2.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f); cb2.BeginText(); cb2.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "NIP :", 17, 271, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PUNKT SPRZEDAŻY :", 9, 261, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PRACOWNIK :", 8, 251, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "DATA :", 19, 241, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "9283456172", 190, 271, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, pokUserInfo.FirstOrDefault().POK.ToString(), 190, 261, 0); //163 cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, pokUserInfo.FirstOrDefault().Name + " " + pokUserInfo.FirstOrDefault().Surname, 190, 251, 0); //142 cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, now2, 190, 241, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "NETTO :", 8, 75, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "VAT :", 8, 65, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_CENTER, VATAMOUNT + " %", 50, 65, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TYP PŁATNOŚCI :", 8, 50, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "zł " + NETTO, 190, 75, 0); cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "zł " + VAT, 190, 65, 0); if (this.CardBool == true) { cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Karta", 190, 50, 0); } else if (this.CashBool == true) { cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Gotówka", 190, 50, 0); } else if (transferBOOL == true) { cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Przelew bankowy", 190, 50, 0); } ColumnText ct = new ColumnText(cb2); Phrase longtxt = new Phrase(productDesc); ct.SetSimpleColumn(longtxt, 8, 184, 192, 10, 11, Element.ALIGN_LEFT); ct.Go(); cb2.EndText(); cb2.RestoreState(); PdfContentByte cb3 = writer.DirectContent; cb3.SaveState(); cb3.SetColorFill(BaseColor.BLACK); cb3.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 9f); cb3.BeginText(); cb3.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Potwierdzenie KP", 100, 228, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "DATA WAŻNOŚCI :", 8, 130, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "OD :", 8, 120, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "DO :", 8, 110, 0); if (activeDate != "") { cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, activeDate, 32, 120, 0);//dodac } else { cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BRAK", 32, 120, 0);//dodac } if (validationTime != "") { cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, validationTime, 32, 110, 0);//dodac } else { cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BRAK", 32, 110, 0);//dodac } cb3.EndText(); cb3.RestoreState(); PdfContentByte cb4 = writer.DirectContent; cb4.SaveState(); cb4.SetColorFill(BaseColor.BLACK); cb4.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12f); cb4.BeginText(); cb4.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "SUMA :", 8, 85, 0); cb4.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "zł " + BRUTTO, 190, 85, 0); cb4.EndText(); cb4.RestoreState(); pdfDoc.Close(); } }
static int borderThickness = 1; // It's just 1. Won't really change, but whatever. If you change it, things will get fucky. public static bool MakePDF(Ragecomic comic, string pdffile) { using (System.IO.FileStream fs = new FileStream(pdffile, FileMode.Create)) { int rows = (int)Math.Ceiling((double)comic.panels / 2); int width = rowWidth * 2 + borderThickness * 3; int height = rowHeight * rows + borderThickness * rows + borderThickness; // 239 per row, plus 1 pixel border per row, plus 1 pixel extra border ZipFile drawImageZip = new ZipFile(); bool hasDrawImages = comic.items.getDrawImageCount() > 0; if (hasDrawImages) { drawImageZip.Dispose(); string addition = ""; int nr = 1; while (File.Exists(pdffile + ".drawimages" + addition + ".zip")) { addition = "_" + (nr++).ToString(); } drawImageZip = new ZipFile(pdffile + ".drawimages" + addition + ".zip"); } // Create an instance of the document class which represents the PDF document itself. Rectangle pageSize = new Rectangle(width, height); Document document = new Document(pageSize, 0, 0, 0, 0); // 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(document, fs); document.AddAuthor("Derp"); document.AddCreator("RagemakerToPDF"); document.AddKeywords("rage, comic"); document.AddSubject("A rage comic"); document.AddTitle("A rage comic"); // Open the document to enable you to write to the document document.Open(); PdfContentByte cb = writer.DirectContent; // Fill background with white Rectangle rect = new iTextSharp.text.Rectangle(0, 0, width, height); rect.BackgroundColor = new BaseColor(255, 255, 255); cb.Rectangle(rect); // Draw grid on bottom if it isn't set to be on top. if (!comic.gridAboveAll && comic.showGrid) { DrawGrid(cb, width, height, rows, comic); } //List<MyMedia.FontFamily> families = MyMedia.Fonts.SystemFontFamilies.ToList(); // This was a neat idea, but it's much too slow //List<string> files = FontFinder.GetFilesForFont("Courier New").ToList(); //string filename = FontFinder.GetSystemFontFileName(families[0].) //Draw.Font testFont = new Draw.Font(new Draw.FontFamily("Courier New"),12f,Draw.FontStyle.Regular | Draw.FontStyle.Bold); string courierPath = FontFinder.GetSystemFontFileName("Courier New", true); string courierBoldPath = FontFinder.GetSystemFontFileName("Courier New", true, Draw.FontStyle.Bold); string tahomaPath = FontFinder.GetSystemFontFileName("Tahoma", true, Draw.FontStyle.Bold); // Define base fonts Font[] fonts = new Font[3]; fonts[0] = new Font(BaseFont.CreateFont(courierPath, BaseFont.CP1252, BaseFont.EMBEDDED)); fonts[1] = new Font(BaseFont.CreateFont(courierBoldPath, BaseFont.CP1252, BaseFont.EMBEDDED)); fonts[2] = new Font(BaseFont.CreateFont(tahomaPath, BaseFont.CP1252, BaseFont.EMBEDDED)); /*fonts[0] = BaseFont.CreateFont("fonts/TRCourierNew.ttf", BaseFont.CP1252, BaseFont.EMBEDDED); * fonts[1] = BaseFont.CreateFont("fonts/TRCourierNewBold.ttf", BaseFont.CP1252, BaseFont.EMBEDDED); * fonts[2] = new Font(BaseFont.CreateFont("fonts/Tahoma-Bold.ttf", BaseFont.CP1252, BaseFont.EMBEDDED));*/ int drawimageindex = 0; int index = 0; foreach (var item in comic.items) { if (item is Face) { Face face = (Face)item; Image pdfImage; System.Drawing.Image faceImage; // If mirroring is necessary, we have to read the image via C# and use RotateFlip, as iTextSharp doesn't support mirroring. if (face.mirrored) { // If it's a JPEG, open it with Flux.JPEG.Core, because the internal JPEG decoder (and also LibJpeg.NET) creates weird dithering artifacts with greyscale JPGs, which some of the rage faces are. if (Path.GetExtension(face.file).ToLower() == ".jpeg" || Path.GetExtension(face.file).ToLower() == ".jpg") { FileStream jpegstream = File.OpenRead("images/" + face.file); FluxJpeg.Core.DecodedJpeg myJpeg = new JpegDecoder(jpegstream).Decode(); // Only use this JPEG decoder if the colorspace is Gray. Otherwise the normal one is just fine. if (myJpeg.Image.ColorModel.colorspace == FluxJpeg.Core.ColorSpace.Gray) { myJpeg.Image.ChangeColorSpace(FluxJpeg.Core.ColorSpace.YCbCr); faceImage = myJpeg.Image.ToBitmap(); } else { faceImage = System.Drawing.Image.FromFile("images/" + face.file); } } else { faceImage = System.Drawing.Image.FromFile("images/" + face.file); } // Apply mirroring faceImage.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipX); pdfImage = Image.GetInstance(faceImage, System.Drawing.Imaging.ImageFormat.Png); } else { // Just let iTextSharp handle it if no mirroring is required. Will also save space (presumably) pdfImage = Image.GetInstance("images/" + face.file); } pdfImage.ScalePercent(face.scalex * 100, face.scaley * 100); pdfImage.Rotation = -(float)Math.PI * face.rotation / 180.0f; pdfImage.SetAbsolutePosition(item.x, (height - item.y) - pdfImage.ScaledHeight); // Set opacity to proper value if (face.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = face.opacity; cb.SetGState(graphicsState); } cb.AddImage(pdfImage); // Set back to normal if (face.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = 1f; cb.SetGState(graphicsState); } } else if (item is DrawImage) { DrawImage drawimage = (DrawImage)item; drawImageZip.AddEntry("drawimage_" + (drawimageindex++).ToString() + ".png", drawimage.imagedata); System.Drawing.Image pngImage = System.Drawing.Image.FromStream(new MemoryStream(drawimage.imagedata)); Image pdfImage = Image.GetInstance(pngImage, System.Drawing.Imaging.ImageFormat.Png); // Rotation is NOT to be applied. Ragemaker actually has a bug that causes it to save rotated images in their rotated form, but save the rotation value anyway // Thus rotating the image by the rotation value will actually rotate them double compared to what they originally looked like // The irony is that ragemaker *itself* cannot properly load an xml it created with this rotation value, as it will also apply the rotation // As such, this tool is currently the only way to correctly display that .xml file as it was originally meant to look, not even ragemaker itself can properly load it again. //pdfImage.Rotation = -(float)Math.PI * item.rotation / 180.0f; pdfImage.SetAbsolutePosition(item.x, (height - item.y) - pdfImage.ScaledHeight); // Opacity likewise seems to be baked in, and in fact the opacity value doesn't even exist. // Implementing it anyway, in case it ever becomes a thing. if (drawimage.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = drawimage.opacity; cb.SetGState(graphicsState); } cb.AddImage(pdfImage); // Set back to normal if (drawimage.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = 1f; cb.SetGState(graphicsState); } } else if (item is Text) { int padding = 4; Text text = (Text)item; // Create template PdfTemplate xobject = cb.CreateTemplate(text.width, text.height); // Background color (if set) if (text.bgOn) { Rectangle bgRectangle = new Rectangle(0, 0, text.width, text.height); System.Drawing.Color bgColor = System.Drawing.ColorTranslator.FromHtml(text.bgColor); rect.BackgroundColor = new BaseColor(bgColor.R, bgColor.G, bgColor.B, (int)Math.Floor(text.opacity * 255)); xobject.Rectangle(rect); } // Create text Rectangle textangle = new Rectangle(padding, 0, text.width - padding, text.height); ColumnText ct = new ColumnText(xobject); ct.SetSimpleColumn(textangle); Paragraph paragraph = new Paragraph(text.text); Font myFont = fonts[text.style]; // More specific treatment if it's an AnyFont element which allows the user to select any font and styles, not just the normal 3 presets // This isn't perfect, as the current FontFinder doesn't indicate whether he actually found an Italic/Bold typeface, hence it's not possible // to determine whether faux-italic/faux-bold should be applied. Currently it will only work correctly if each used font has a specific typeface // for the needed styles (bold or italic), otherwise incorrect results. // TODO Fix, for example let FontFinder return array of strings, one of which is indicating the suffix that was found. if (text is AnyFontText) { AnyFontText anyfont = (AnyFontText)text; string fontname = anyfont.font; string fontfile = ""; if (anyfont.bold) { fontfile = FontFinder.GetSystemFontFileName(fontname, true, Draw.FontStyle.Bold); int fontStyle = 0; if (anyfont.italic) { fontStyle |= Font.ITALIC; } if (anyfont.underline) { fontStyle |= Font.UNDERLINE; } myFont = new Font(BaseFont.CreateFont(fontfile, BaseFont.CP1252, BaseFont.EMBEDDED), 100f, fontStyle); } else if (anyfont.italic) { fontfile = FontFinder.GetSystemFontFileName(fontname, true, Draw.FontStyle.Italic); int fontStyle = 0; if (anyfont.underline) { fontStyle |= Font.UNDERLINE; } myFont = new Font(BaseFont.CreateFont(fontfile, BaseFont.CP1252, BaseFont.EMBEDDED), 100f, fontStyle); } else { fontfile = FontFinder.GetSystemFontFileName(fontname, true, Draw.FontStyle.Regular); int fontStyle = 0; if (anyfont.underline) { fontStyle |= Font.UNDERLINE; } myFont = new Font(BaseFont.CreateFont(fontfile, BaseFont.CP1252, BaseFont.EMBEDDED), 100f, fontStyle); } } myFont.Size = text.size; System.Drawing.Color color = (System.Drawing.Color)(new System.Drawing.ColorConverter()).ConvertFromString(text.color); myFont.Color = new BaseColor(color.R, color.G, color.B, (int)Math.Floor(text.opacity * 255)); paragraph.Font = myFont; paragraph.Alignment = text.align == Text.ALIGN.LEFT ? PdfContentByte.ALIGN_LEFT : (text.align == Text.ALIGN.RIGHT ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER); paragraph.SetLeading(0, 1.12f); ct.AddElement(paragraph); ct.Go(); // Angle to radians float angle = (float)Math.PI * text.rotation / 180.0f; // Calculate Bounding Box size for correct placement later GraphicsPath gp = new GraphicsPath(); gp.AddRectangle(new System.Drawing.Rectangle(0, 0, (int)Math.Round(text.width), (int)Math.Round(text.height))); Matrix translateMatrix = new Matrix(); translateMatrix.RotateAt(text.rotation, new System.Drawing.PointF(text.width / 2, text.height / 2)); gp.Transform(translateMatrix); var gbp = gp.GetBounds(); float newWidth = gbp.Width, newHeight = gbp.Height; // Create correct placement // Background info: I rotate around the center of the text box, thus the center of the text box is what I attempt to place correctly with the initial .Translate() AffineTransform transform = new AffineTransform(); transform.Translate(item.x + newWidth / 2 - text.width / 2, height - (item.y + newHeight / 2 - text.height / 2) - text.height); transform.Rotate(-angle, text.width / 2, text.height / 2); cb.AddTemplate(xobject, transform); } index++; } if (comic.gridAboveAll && comic.showGrid) { DrawGrid(cb, width, height, rows, comic); } //document.Add(new Paragraph("Hello World!")); // Close the document document.Close(); // Close the writer instance writer.Close(); // Always close open filehandles explicity fs.Close(); if (hasDrawImages) { drawImageZip.Save(); } drawImageZip.Dispose(); } return(false); }
public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document) { ColumnText.ShowTextAligned(total, Element.ALIGN_LEFT, new Phrase((writer.CurrentPageNumber - 1).ToString(), font2), 4, 4, 0); }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PdfVersion = PdfWriter.VERSION_1_5; // step 3 document.Open(); // step 4 PdfContentByte cb = writer.DirectContent; PdfLayer nested = new PdfLayer("Nested layers", writer); PdfLayer nested_1 = new PdfLayer("Nested layer 1", writer); PdfLayer nested_2 = new PdfLayer("Nested layer 2", writer); nested.AddChild(nested_1); nested.AddChild(nested_2); writer.LockLayer(nested_2); cb.BeginLayer(nested); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layers"), 50, 775, 0 ); cb.EndLayer(); cb.BeginLayer(nested_1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layer 1"), 100, 800, 0 ); cb.EndLayer(); cb.BeginLayer(nested_2); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layer 2"), 100, 750, 0 ); cb.EndLayer(); PdfLayer group = PdfLayer.CreateTitle("Grouped layers", writer); PdfLayer layer1 = new PdfLayer("Group: layer 1", writer); PdfLayer layer2 = new PdfLayer("Group: layer 2", writer); group.AddChild(layer1); group.AddChild(layer2); cb.BeginLayer(layer1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("layer 1 in the group"), 50, 700, 0 ); cb.EndLayer(); cb.BeginLayer(layer2); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("layer 2 in the group"), 50, 675, 0 ); cb.EndLayer(); PdfLayer radiogroup = PdfLayer.CreateTitle("Radio group", writer); PdfLayer radio1 = new PdfLayer("Radiogroup: layer 1", writer); radio1.On = true; PdfLayer radio2 = new PdfLayer("Radiogroup: layer 2", writer); radio2.On = false; PdfLayer radio3 = new PdfLayer("Radiogroup: layer 3", writer); radio3.On = false; radiogroup.AddChild(radio1); radiogroup.AddChild(radio2); radiogroup.AddChild(radio3); List <PdfLayer> options = new List <PdfLayer>(); options.Add(radio1); options.Add(radio2); options.Add(radio3); writer.AddOCGRadioGroup(options); cb.BeginLayer(radio1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("option 1"), 50, 600, 0 ); cb.EndLayer(); cb.BeginLayer(radio2); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("option 2"), 50, 575, 0 ); cb.EndLayer(); cb.BeginLayer(radio3); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase( "option 3" ), 50, 550, 0 ); cb.EndLayer(); PdfLayer not_printed = new PdfLayer("not printed", writer); not_printed.OnPanel = false; not_printed.SetPrint("Print", false); cb.BeginLayer(not_printed); ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase( "PRINT THIS PAGE" ), 300, 700, 90 ); cb.EndLayer(); PdfLayer zoom = new PdfLayer("Zoom 0.75-1.25", writer); zoom.OnPanel = false; zoom.SetZoom(0.75f, 1.25f); cb.BeginLayer(zoom); ColumnText.ShowTextAligned( cb, Element.ALIGN_LEFT, new Phrase( "Only visible if the zoomfactor is between 75 and 125%" ), 30, 530, 90 ); cb.EndLayer(); } }
/** * Get the <code>PdfAppearance</code> of a list field * @throws IOException on error * @throws DocumentException on error * @return A <code>PdfAppearance</code> */ internal PdfAppearance GetListAppearance() { PdfAppearance app = GetBorderAppearance(); app.BeginVariableText(); if (choices == null || choices.Length == 0) { app.EndVariableText(); return(app); } int topChoice = choiceSelection; if (topChoice >= choices.Length) { topChoice = choices.Length - 1; } if (topChoice < 0) { topChoice = 0; } BaseFont ufont = RealFont; float usize = fontSize; if (usize == 0) { usize = 12; } bool borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET; float h = box.Height - borderWidth * 2; float offsetX = borderWidth; if (borderExtra) { h -= borderWidth * 2; offsetX *= 2; } float leading = ufont.GetFontDescriptor(BaseFont.BBOXURY, usize) - ufont.GetFontDescriptor(BaseFont.BBOXLLY, usize); int maxFit = (int)(h / leading) + 1; int first = 0; int last = 0; last = topChoice + maxFit / 2 + 1; first = last - maxFit; if (first < 0) { last += first; first = 0; } // first = topChoice; last = first + maxFit; if (last > choices.Length) { last = choices.Length; } topFirst = first; app.SaveState(); app.Rectangle(offsetX, offsetX, box.Width - 2 * offsetX, box.Height - 2 * offsetX); app.Clip(); app.NewPath(); Color fcolor = (textColor == null) ? GrayColor.GRAYBLACK : textColor; app.SetColorFill(new Color(10, 36, 106)); app.Rectangle(offsetX, offsetX + h - (topChoice - first + 1) * leading, box.Width - 2 * offsetX, leading); app.Fill(); float xp = offsetX * 2; float yp = offsetX + h - ufont.GetFontDescriptor(BaseFont.BBOXURY, usize); for (int idx = first; idx < last; ++idx, yp -= leading) { String ptext = choices[idx]; int rtl = CheckRTL(ptext) ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_NO_BIDI; ptext = RemoveCRLF(ptext); Phrase phrase = ComposePhrase(ptext, ufont, (idx == topChoice) ? GrayColor.GRAYWHITE : fcolor, usize); ColumnText.ShowTextAligned(app, Element.ALIGN_LEFT, phrase, xp, yp, 0, rtl, 0); } app.RestoreState(); app.EndVariableText(); return(app); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; if (MeetingId.HasValue) { meeting = DbUtil.Db.Meetings.Single(mt => mt.MeetingId == MeetingId); Debug.Assert(meeting.MeetingDate != null, "meeting.MeetingDate != null"); NewMeetingInfo = new NewMeetingInfo { MeetingDate = meeting.MeetingDate.Value }; } var list1 = NewMeetingInfo.ByGroup ? ReportList2().ToList() : ReportList().ToList(); if (!list1.Any()) { Response.Write("no data found"); return; } Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "filename=foo.pdf"); doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64); var w = PdfWriter.GetInstance(doc, Response.OutputStream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; box = new PdfPCell(); box.Border = Rectangle.NO_BORDER; box.CellEvent = new CellEvent(); OrgInfo lasto = null; foreach (var o in list1) { lasto = o; var table = new PdfPTable(1); table.DefaultCell.Border = Rectangle.NO_BORDER; table.DefaultCell.Padding = 0; table.WidthPercentage = 100; if (meeting != null) { var q = from at in meeting.Attends where at.AttendanceFlag || AttendCommitmentCode.committed.Contains(at.Commitment ?? 0) orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new { at.MemberType.Code, Name2 = NewMeetingInfo.UseAltNames && at.Person.AltName.HasValue() ? at.Person.AltName : at.Person.Name2, at.PeopleId, at.Person.DOB }; if (q.Any()) { StartPageSet(o); } foreach (var a in q) { table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font)); } } else if (OrgSearchModel != null) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == o.OrgId join m in DbUtil.Db.OrgPeople(o.OrgId, o.Groups) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } else if (Filter?.GroupSelect == GroupSelectCode.Member) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == Filter.Id join m in DbUtil.Db.OrgFilterPeople(QueryId, null) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now where NewMeetingInfo.ByGroup == false || m.Groups.Contains((char)10 + o.Groups + (char)10) orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } else { var q = from m in DbUtil.Db.OrgFilterPeople(QueryId, null) orderby m.Name2 let p = DbUtil.Db.People.Single(pp => pp.PeopleId == m.PeopleId) let om = p.OrganizationMembers.SingleOrDefault(mm => mm.OrganizationId == Filter.Id) let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om == null ? "Guest" : om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } if ((OrgSearchModel != null && NewMeetingInfo.ByGroup == false) || (Filter != null && Filter.GroupSelect == GroupSelectCode.Member && meeting == null && !Filter.SgFilter.HasValue() && !Filter.NameFilter.HasValue() && !Filter.FilterIndividuals == true && !Filter.FilterTag == true && NewMeetingInfo.ByGroup == false)) { foreach (var m in RollsheetModel.FetchVisitors(o.OrgId, NewMeetingInfo.MeetingDate, true, NewMeetingInfo.UseAltNames)) { if (table.Rows.Count == 0) { StartPageSet(o); } table.AddCell(AddRow(m.VisitorType, m.Name2, m.PeopleId, m.BirthDate, "", boldfont)); } } if (!pageSetStarted) { continue; } var col = 0; var gutter = 20f; var colwidth = (doc.Right - doc.Left - gutter) / 2; var ct = new ColumnText(w.DirectContent); ct.AddElement(table); var status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, doc.Top); } else { ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, doc.Top); } status = ct.Go(); ++col; if (col > 1) { col = 0; doc.NewPage(); } } } if (!hasRows) { if (!pageSetStarted) { StartPageSet(lasto); } doc.Add(new Paragraph("no members as of this meeting date and time to show on rollsheet")); } doc.Close(); }
public void SetTextAndDescriptions(string fieldName, bool nameOnly, string text, IEnumerable <IInfoText> values, string textAfter = null) { if (preserveEdit) { SetField(fieldName, (text != null ? text + "\n" : "") + String.Join("\n", values.Select(f => f.ToInfo(!nameOnly))) + (textAfter != null ? "\n" + textAfter : "")); } else { int j = 0; float[] pos = stamper.AcroFields.GetFieldPositions(fieldName); for (int i = 0; i < pos.Length - 4; i += 5) { var item = stamper.AcroFields.GetFieldItem(fieldName); var dic = item.GetMerged(j >= item.Size ? 0 : j); TextField t = new TextField(null, null, null); stamper.AcroFields.DecodeGenericDictionary(dic, t); j++; float size = 8; while (size > 2) { ColumnText currentColumnText = new ColumnText(stamper.GetOverContent((int)pos[i])); currentColumnText.SetSimpleColumn(pos[i + 1], pos[i + 2], pos[i + 3], pos[i + 4]); currentColumnText.SetLeading(0, 1); currentColumnText.Alignment = Element.ALIGN_JUSTIFIED; var bold = FontFactory.GetFont("Helvetica", size, Font.BOLD); var reg = FontFactory.GetFont("Helvetica", size, Font.NORMAL); if (t.Font != null) { bold = FontFactory.GetFont(t.Font.FullFontName[0][3], size, Font.BOLD); reg = FontFactory.GetFont(t.Font.FullFontName[0][3], size, Font.NORMAL); } if (text != null) { currentColumnText.AddElement(new Paragraph(text, reg) { Leading = 0, MultipliedLeading = 1, SpacingAfter = size / 2 }); } foreach (IInfoText f in values) { Paragraph p = new Paragraph(f.InfoTitle + (nameOnly ? "" : ":"), bold); if (!nameOnly) { p.Font = reg; p.SpacingAfter = size / 2; p.SetLeading(0, 1); p.Add(f.InfoText.Trim(new char[] { ' ', '\r', '\n', '\t' })); } currentColumnText.AddElement(p); } if (textAfter != null) { currentColumnText.AddElement(new Paragraph(textAfter, reg) { Leading = 0, MultipliedLeading = 1 }); } int res = currentColumnText.Go(true); if (res == ColumnText.NO_MORE_COLUMN) { size -= 0.5f; } else { break; } } { ColumnText currentColumnText = new ColumnText(stamper.GetOverContent((int)pos[i])); currentColumnText.SetSimpleColumn(pos[i + 1], pos[i + 2], pos[i + 3], pos[i + 4]); currentColumnText.SetLeading(0, 1); currentColumnText.Alignment = Element.ALIGN_JUSTIFIED; var bold = FontFactory.GetFont("Helvetica", size, Font.BOLD); var reg = FontFactory.GetFont("Helvetica", size, Font.NORMAL); if (t.Font != null) { bold = FontFactory.GetFont(t.Font.FullFontName[0][3], size, Font.BOLD); reg = FontFactory.GetFont(t.Font.FullFontName[0][3], size, Font.NORMAL); } if (text != null) { currentColumnText.AddElement(new Paragraph(text, reg) { Leading = 0, MultipliedLeading = 1, SpacingAfter = size / 2 }); } foreach (IInfoText f in values) { Paragraph p = new Paragraph(f.InfoTitle + (nameOnly ? "" : ":"), bold); if (!nameOnly) { p.Font = reg; p.SpacingAfter = size / 2; p.SetLeading(0, 1); p.Add(f.InfoText.Trim(new char[] { ' ', '\r', '\n', '\t' })); } currentColumnText.AddElement(p); } if (textAfter != null) { currentColumnText.AddElement(new Paragraph(textAfter, reg) { Leading = 0, MultipliedLeading = 1 }); } currentColumnText.Go(); } } } }
public void OnEndPage(PdfWriter writer, Document document) { PdfContentByte cOver = writer.DirectContent; PdfContentByte cUnder = writer.DirectContentUnder; if (document.PageNumber > 0) { //insert watermark if (!string.IsNullOrEmpty(config.Watermark)) { ColumnText.ShowTextAligned( cUnder, Element.ALIGN_CENTER, new Paragraph(config.Watermark, config.WatermarkFont) { }, (document.Left + document.Right) / 2, (document.Top + document.Bottom) / 2, (float)(Math.Atan2(document.Top - document.Bottom, document.Right - document.Left) * 180 / Math.PI)); } //insert task number if (!string.IsNullOrEmpty(config.TaskNumber)) { ColumnText.ShowTextAligned( cOver, Element.ALIGN_RIGHT, new Paragraph(config.TaskNumber, config.TaskNumberFont), document.Right, document.Top - config.TaskNumberFont.Size / 2, 0); } //insert header //left if (!string.IsNullOrEmpty(config.HeaderLeft)) { ColumnText.ShowTextAligned( cOver, Element.ALIGN_LEFT, new Paragraph(config.HeaderLeft, config.HeaderFont), document.Left, document.Top + config.MarginHeader + config.HeaderFont.Size / 2, 0); } //center if (!string.IsNullOrEmpty(config.HeaderCenter)) { ColumnText.ShowTextAligned( cOver, Element.ALIGN_CENTER, new Paragraph(config.HeaderCenter, config.HeaderFont), document.PageSize.Width / 2, document.Top + config.MarginHeader + config.HeaderFont.Size / 2, 0); } //right if (!string.IsNullOrEmpty(config.HeaderRight)) { ColumnText.ShowTextAligned( cOver, Element.ALIGN_RIGHT, new Paragraph(config.HeaderRight, config.HeaderFont), document.Right, document.Top + config.MarginHeader + config.HeaderFont.Size / 2, 0); } if (!string.IsNullOrEmpty(config.HeaderLeft) || !string.IsNullOrEmpty(config.HeaderCenter) || !string.IsNullOrEmpty(config.HeaderRight)) { cOver.MoveTo(document.Left, document.Top + config.MarginHeader); cOver.LineTo(document.Right, document.Top + config.MarginHeader); cOver.Stroke(); } //insert footer //left if (!string.IsNullOrEmpty(config.FooterLeft)) { ColumnText.ShowTextAligned( cOver, Element.ALIGN_LEFT, new Paragraph(config.FooterLeft, config.FooterFont), document.Left, document.Bottom - config.MarginFooter - config.FooterFont.Size, 0); } //center if (!string.IsNullOrEmpty(config.FooterCenter)) { ColumnText.ShowTextAligned( cOver, Element.ALIGN_CENTER, new Paragraph(config.FooterCenter, config.FooterFont), document.PageSize.Width / 2, document.Bottom - config.MarginFooter - config.FooterFont.Size, 0); } else { //page number ColumnText.ShowTextAligned( cOver, Element.ALIGN_CENTER, new Paragraph(writer.PageNumber.ToString("Page 0"), config.FooterFont), document.PageSize.Width / 2, document.Bottom - config.MarginFooter - config.FooterFont.Size, 0); } //right if (!string.IsNullOrEmpty(config.FooterRight)) { ColumnText.ShowTextAligned( cOver, Element.ALIGN_RIGHT, new Paragraph(config.FooterRight, config.FooterFont), document.Right, document.Bottom - config.MarginFooter - config.FooterFont.Size, 0); } cOver.MoveTo(document.Left, document.Bottom - config.MarginFooter); cOver.LineTo(document.Right, document.Bottom - config.MarginFooter); cOver.Stroke(); } }
public static byte[] AssinarPdf(X509Certificate2 certificate, DadosAssinatura dadosAssinatura) { try { // ler arquivo e insere dados de assinatura using (PdfReader reader = new PdfReader(dadosAssinatura.ArquivoPdf)) { using (MemoryStream fout = new MemoryStream()) { PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0'); // texto marca d'água Font f = new Font(Font.FontFamily.UNDEFINED, 10); Phrase pAssinado = new Phrase("Assinado digitalmente por:", f); string[] dados = certificate.GetNameInfo(X509NameType.SimpleName, false).Split(':'); Phrase pNome = new Phrase(dados[0], f); Phrase pDocumento = new Phrase(dados[1], f); Phrase pData = new Phrase(certificate.GetEffectiveDateString(), f); Phrase pServico = new Phrase(dadosAssinatura.Servico, f); // Imagem marca d'água Image img = dadosAssinatura.Imagem; float w = 200F; float h = 75.2F; // Transparência PdfGState gs1 = new PdfGState(); // Propriedades PdfContentByte over; Rectangle pagesize; int n = reader.NumberOfPages; //Página var pagina = 1; pagesize = reader.GetPageSizeWithRotation(pagina); switch (dadosAssinatura.PaginaAssinatura) { case EnumPaginaAssinatura.PRIMEIRA: pagina = 1; break; case EnumPaginaAssinatura.ULTIMA: pagina = reader.NumberOfPages; break; default: pagina = 1; break; } float x, y, xr = 0, hr = 0, yr = 0, wr = 0; //Posição da assinatura switch (dadosAssinatura.Posicao) { case EnumPosicao.ACIMA_ESQUERDA: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Top * 0.88); xr = x * 0.5F; wr = w; yr = pagesize.Top * 0.97F; hr = pagesize.Top * 0.88F; break; case EnumPosicao.ACIMA_DIREITA: x = (float)(pagesize.Right * 0.64); y = (float)(pagesize.Top * 0.88); xr = pagesize.Right * 0.97F; wr = xr - w; yr = pagesize.Top * 0.97F; hr = pagesize.Top * 0.88F; break; case EnumPosicao.ABAIXO_ESQUERDA: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Bottom * 0.88); xr = x * 0.5F; wr = w; yr = y; hr = h; break; case EnumPosicao.ABAIXO_DIREITA: x = (float)(pagesize.Right * 0.64); y = (float)(pagesize.Bottom * 0.88); xr = x * 1.53F; wr = w * 1.9F; yr = y; hr = h; break; default: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Top * 0.88); xr = x * 1.53F; wr = w * 1.9F; break; } //Plota a assinatura no pdf over = stamper.GetOverContent(pagina); over.SaveState(); over.SetGState(gs1); over.AddImage(img, w, 0, 0, h, x, y); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pAssinado, x + 10, y + 60, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pNome, x + 10, y + 50, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pDocumento, x + 10, y + 40, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pData, x + 10, y + 25, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pServico, x + 10, y + 10, 0); over.RestoreState(); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; appearance.Layer2Text = ""; appearance.Layer4Text = ""; Rectangle rect = new Rectangle(wr, hr, xr, yr); appearance.SetVisibleSignature(rect, pagina, "Assinatura Digital"); ICollection <Org.BouncyCastle.X509.X509Certificate> certChain; IExternalSignature es = ResolveExternalSignatureFromCertStore(certificate, dadosAssinatura.CertificadoValido, out certChain); //Autenticação da assinatura digital MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CADES); stamper.Close(); return(fout.ToArray()); } } } catch (Exception ex) { System.Diagnostics.Trace.TraceError("Erro durante assinatura digital do pdf: {0}", ex.Message); throw; } }
/// <summary> /// Returns a memory stream for a combined document, comprising all the supplied pdf documents /// </summary> /// <param name="documents">The documents to combine</param> /// <returns>The memory stream for the combined document</returns> public MemoryStream PdfDocumentCombinedStream(IList <Document> documents) { // If we have no documents at all, do not proceed if (documents.Count == 0) { return(null); } // Initialise the new PDF document object to create, the output stream to write its data to, and the PdfSmartCopy writer var combinedDocument = new iTextSharp.text.Document(); var oCombinedDocumentStream = new MemoryStream(); var pdfWriter = new PdfSmartCopy(combinedDocument, oCombinedDocumentStream); // Set compression options pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); pdfWriter.CompressionLevel = PdfStream.BEST_COMPRESSION; pdfWriter.SetFullCompression(); // Open document object to write to - this is the actual object that gets created and modified in memoey // The pdf writer outputs this to the memory stream (if we wanted to, we could just as easily write to a file instead) combinedDocument.Open(); // Iterate through all pdf documents in the collection foreach (var document in documents) { var oStream = new MemoryStream(); // Read individual document content var reader = new PdfReader(document.LatestRevision.Content.Content); // Create a pdf stamper to modify the content and output it to a memory stream // We set it to flatten the form field data in the output, so it cannot be modified // Note that text fields are flattened explicitly later in the method // so the only form fields that actually get flattened are radio buttons, check boxes etc var stamper = new PdfStamper(reader, oStream) { FormFlattening = true }; var form = stamper.AcroFields; var keys = new ArrayList(form.Fields.Keys.ToList()); // Create an arial base font // We use this during flattening of text fields var arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); var arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); foreach (var key in keys) { if (form.GetFieldType(key.ToString()) == 4) { // Text field // Render the form field content as a replacement text (Phrase) object // We do this here as the built-in FormFlattening option causes a font error in the final pdf const float fontSize = 8.0f; const float leading = 8.0f; const float minimumHeight = 12.5f; const float adjustmentY = 1.5f; // Get field positioning information var fieldPositions = form.GetFieldPositions(key.ToString()); if (fieldPositions.Count == 0) { break; } var fieldPosition = fieldPositions[0]; var height = fieldPosition.position.Top - fieldPosition.position.Bottom; var width = fieldPosition.position.Right - fieldPosition.position.Left; var heightAdjustment = height < minimumHeight ? minimumHeight - height : 0.0f; // Generate the Phrase object which holds the rendered text, and populate it using the contents of the form field var phrase = new Phrase(leading, form.GetField(key.ToString()), new iTextSharp.text.Font(arialBaseFont, fontSize)); // Table object to hold the Phrase // This allows us to set the vertical and horizontal alignment of each rendered Phrase var table = new PdfPTable(1) { WidthPercentage = 100 }; table.SetWidths(new[] { width }); // Table cell object in which the Phrase will be positioned var cell = new PdfPCell { FixedHeight = height + heightAdjustment, Border = iTextSharp.text.Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.AddElement(phrase); table.AddCell(cell); // We now create our ColumnText wrapper, which allows us to position the table in the same place as the original form field var columnText = new ColumnText(stamper.GetOverContent(fieldPosition.page)); columnText.SetSimpleColumn(fieldPosition.position.Left, fieldPosition.position.Bottom + adjustmentY - heightAdjustment, fieldPosition.position.Right, fieldPosition.position.Top + adjustmentY); columnText.AddElement(table); columnText.Go(); // Finally, all that is left to do is to remove the original form field form.RemoveField(key.ToString()); } else { // Non-text field // Append each form field name to have a unique suffix // This is so that when we join all the documents together, all the form field names are unique and therefore still rendered correctly form.RenameField(key.ToString(), string.Format("{0}{1}", key, documents.IndexOf(document))); } } // We now compress all images in the pdf // http://cjhaas.com/blog/2012/01/06/how-to-recompress-images-in-a-pdf-using-itextsharp/ const int physicalSizePercentage = 90; const int compressionPercentage = 85; var numberOfPages = reader.NumberOfPages; for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { // Get the XObject structure var resources = (PdfDictionary)PdfReader.GetPdfObject(reader.GetPageN(currentPageIndex).Get(PdfName.RESOURCES)); var xObjects = (PdfDictionary)PdfReader.GetPdfObject(resources.Get(PdfName.XOBJECT)); if (xObjects != null) { // Loop through each XObject key foreach (var key in xObjects.Keys) { var xObject = xObjects.Get(key); if (xObject.IsIndirect()) { // Get the current key as a pdf object var imgObject = (PdfDictionary)PdfReader.GetPdfObject(xObject); // Is the object an image? if (imgObject != null && imgObject.Get(PdfName.SUBTYPE).Equals(PdfName.IMAGE)) { // Note: There are several different types of filters we're only handing the simplest one here which is basically raw jpeg if (imgObject.Get(PdfName.FILTER).Equals(PdfName.DCTDECODE)) { // Get the raw bytes of the image var oldBytes = PdfReader.GetStreamBytesRaw((PRStream)imgObject); byte[] newBytes; // Wrap a stream around our original image using (var memoryStream = new MemoryStream(oldBytes)) { // Convert the bytes into a .NET image using (var oldImage = System.Drawing.Image.FromStream(memoryStream)) { // Shrink the source image to a percentage of its original size using (var newImage = ShrinkImage(oldImage, physicalSizePercentage / 100.0f)) { // Convert the image to bytes using jpeg newBytes = ConvertImageToBytes(newImage, compressionPercentage); } } } // Create a new iTextSharp image from our bytes var compressedImage = Image.GetInstance(newBytes); // Kill off the old image PdfReader.KillIndirect(xObject); // Add our image in its place stamper.Writer.AddDirectImageSimple(compressedImage, (PRIndirectReference)xObject); } } } } } } stamper.Writer.CloseStream = false; stamper.Close(); // Read modified document content from the pdf stamper's output stream reader = new PdfReader(oStream.ToArray()); numberOfPages = reader.NumberOfPages; // Add each modified page to our combined document object for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { var page = pdfWriter.GetImportedPage(reader, currentPageIndex); pdfWriter.AddPage(page); } } // Close the pdf writer and the combined document object // This will flush the output memory stream, and give us our completed document data pdfWriter.CloseStream = false; pdfWriter.Close(); combinedDocument.Close(); // Move the stream position to the beginning then return it oCombinedDocumentStream.Seek(0, SeekOrigin.Begin); return(oCombinedDocumentStream); }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 PdfContentByte cb = writer.DirectContent; float gap = (document.PageSize.Width - 400) / 3; PictureBackdrop(gap, 500, cb); PictureBackdrop(200 + 2 * gap, 500, cb); PictureBackdrop(gap, 500 - 200 - gap, cb); PictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb); PictureCircles(gap, 500, cb); cb.SaveState(); PdfGState gs1 = new PdfGState(); gs1.FillOpacity = 0.5f; cb.SetGState(gs1); PictureCircles(200 + 2 * gap, 500, cb); cb.RestoreState(); cb.SaveState(); PdfTemplate tp = cb.CreateTemplate(200, 200); PdfTransparencyGroup group = new PdfTransparencyGroup(); tp.Group = group; PictureCircles(0, 0, tp); cb.SetGState(gs1); cb.AddTemplate(tp, gap, 500 - 200 - gap); cb.RestoreState(); cb.SaveState(); tp = cb.CreateTemplate(200, 200); tp.Group = group; PdfGState gs2 = new PdfGState(); gs2.FillOpacity = 0.5f; gs2.BlendMode = PdfGState.BM_HARDLIGHT; tp.SetGState(gs2); PictureCircles(0, 0, tp); cb.AddTemplate(tp, 200 + 2 * gap, 500 - 200 - gap); cb.RestoreState(); cb.ResetRGBColorFill(); ColumnText ct = new ColumnText(cb); Phrase ph = new Phrase("Ungrouped objects\nObject opacity = 1.0"); ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500, 18, Element.ALIGN_CENTER ); ct.Go(); ph = new Phrase("Ungrouped objects\nObject opacity = 0.5"); ct.SetSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200, 500, 18, Element.ALIGN_CENTER ); ct.Go(); ph = new Phrase( "Transparency group\nObject opacity = 1.0\nGroup opacity = 0.5\nBlend mode = Normal" ); ct.SetSimpleColumn(ph, gap, 0, gap + 200, 500 - 200 - gap, 18, Element.ALIGN_CENTER ); ct.Go(); ph = new Phrase( "Transparency group\nObject opacity = 0.5\nGroup opacity = 1.0\nBlend mode = HardLight" ); ct.SetSimpleColumn(ph, 200 + 2 * gap, 0, 200 + 2 * gap + 200, 500 - 200 - gap, 18, Element.ALIGN_CENTER ); ct.Go(); } }
public static void ReportBuilder(SqlDataReader dr, int cropYear, DateTime letterDate, DateTime deadlineDate, string logoUrl, System.IO.FileStream fs) { const string METHOD_NAME = "ReportBuilder"; const float primaryLeading = 13.5F; const float primaryLeftIndent = 20F; string strLetterDate = letterDate.ToString("MMMM dd, yyyy"); string strDeadlineDate = deadlineDate.ToString("MMMM dd, yyyy"); string LdoBusinessName = ""; string tmpStr = ""; string tmpStr2 = ""; Document document = null; PdfWriter writer = null; LandownerLetterEvent pgEvent = null; ColumnText ct = null; iTextSharp.text.Image imgLogo = null; try { while (dr.Read()) { LdoBusinessName = dr["LdoBusinessName"].ToString(); string LdoAddressLine1 = dr["LdoAddressLine1"].ToString(); string LdoAddressLine2 = dr["LdoAddressLine2"].ToString(); string LdoCityStateZip = dr["LdoCityStateZip"].ToString(); if (document == null) { // IF YOU CHANGE MARGINS, CHANGE YOUR TABLE LAYOUTS !!! // *** US LETTER: 612 X 792 *** document = new Document(PortraitPageSize.PgPageSize, PortraitPageSize.PgLeftMargin, PortraitPageSize.PgRightMargin, PortraitPageSize.PgTopMargin, PortraitPageSize.PgBottomMargin); imgLogo = PdfReports.GetImage(logoUrl, 127, 50, iTextSharp.text.Element.ALIGN_CENTER); // we create a writer that listens to the document // and directs a PDF-stream to a file writer = PdfWriter.GetInstance(document, fs); // Attach my override event handler(s) pgEvent = new LandownerLetterEvent(); pgEvent.FillEvent(imgLogo, strLetterDate, LdoBusinessName, LdoAddressLine1, LdoAddressLine2, LdoCityStateZip); writer.PageEvent = pgEvent; // Open the document document.Open(); } else { pgEvent.FillEvent(imgLogo, strLetterDate, LdoBusinessName, LdoAddressLine1, LdoAddressLine2, LdoCityStateZip); document.NewPage(); } ct = pgEvent.GetColumnObject(); Paragraph p = new Paragraph(primaryLeading, "Your tenant, " + dr["GroBusinessName"].ToString() + ", has indicated that the proceeds for sugar beets grown on your land in\n" + cropYear.ToString() + " are to be split and you will be receiving " + dr.GetDecimal(dr.GetOrdinal("LdoSplitPercent")).ToString("##.0##") + "% of the proceeds. Since Western Sugar Cooperative no\n" + "longer requires signatures for the second payees, this letter has been sent for your verification.\n\n", _normalFont); ct.AddElement(p); p = new Paragraph(new Phrase(primaryLeading, "Your check will be made payable as follows:", _normalFont)); ct.AddElement(p); p = new Paragraph(primaryLeading, dr["ldoPayeeDescription"].ToString(), _normalFont); p.IndentationLeft = primaryLeftIndent; ct.AddElement(p); p = new Paragraph(primaryLeading, "If you have a lien on the beets, the lien holder’s name should be included above.\n\n" + "In addition, the following options were selected by your tenant.", _normalFont); ct.AddElement(p); decimal ldoChemPct = dr.GetDecimal(dr.GetOrdinal("LdoChemicalSplitPct")); if (dr.GetBoolean(dr.GetOrdinal("IsSplitChemical")) && ldoChemPct != 0) { tmpStr = ldoChemPct.ToString("##.0##") + "%"; } else { tmpStr = "No"; } decimal ldoRetainPct = dr.GetDecimal(dr.GetOrdinal("LdoSplitPercent")); if (dr.GetBoolean(dr.GetOrdinal("IsSplitRetain")) && ldoRetainPct != 0) { tmpStr2 = ldoRetainPct.ToString("##.0##") + "% of the"; } else { tmpStr2 = "No"; } p = new Paragraph(primaryLeading, tmpStr2 + " Unit Retains on this contract will be deducted from your proceeds.\n" + tmpStr + " seed & chemical receivables charged to this contract will be deducted from your proceeds.", _normalFont); p.IndentationLeft = primaryLeftIndent; ct.AddElement(p); p = new Paragraph(primaryLeading, "If the above information is correct, no response is needed.\n\n", _normalFont); ct.AddElement(p); p = new Paragraph(primaryLeading, "If any of the above information is not correct, please contact your tenant’s agriculturist, " + dr["AgriculturistName"].ToString() + " at\n" + WSCIEMP.Common.CodeLib.FormatPhoneNumber2Display(dr["AgriculturistPhone"].ToString()) + " by " + strDeadlineDate + ", or mail the corrections to:\n\n", _normalFont); ct.AddElement(p); p = new Paragraph(12F, "Western Sugar Cooperative\n" + "Attn: Marty Smith\n" + "1221 8th Avenue Unit E\n" + "Greeley, CO 80631\n\n", _normalFont); p.IndentationLeft = primaryLeftIndent; ct.AddElement(p); p = new Paragraph(primaryLeading, "Sincerely,\n\n" + "Marty Smith\n" + "Beet Accounting Manager\n\n" + "Ref: " + dr["ContractNo"].ToString(), _normalFont); ct.AddElement(p); ct.Go(false); } // ====================================================== // Close document // ====================================================== if (document != null) { pgEvent.IsDocumentClosing = true; document.Close(); document = null; } if (writer == null || String.IsNullOrEmpty(LdoBusinessName)) { // Warn that we have no data. WSCIEMP.Common.CWarning warn = new WSCIEMP.Common.CWarning("No records matched your report criteria."); throw (warn); } } catch (Exception ex) { string errMsg = "document is null: " + (document == null).ToString() + "; " + "writer is null: " + (writer == null).ToString(); WSCIEMP.Common.CException wscex = new WSCIEMP.Common.CException(MOD_NAME + METHOD_NAME + errMsg, ex); throw (wscex); } finally { if (document != null) { pgEvent.IsDocumentClosing = true; document.Close(); } if (writer != null) { writer.Close(); } } }
public string CreatePDF(int poid) { var po = OrderRepository.Single(poid); if (po == null) { throw new ItemNotFoundException <Ordering.PurchaseOrder>(x => x.POID, poid); } var basePath = ConfigurationManager.AppSettings["PdfBasePath"]; if (string.IsNullOrEmpty(basePath)) { throw new InvalidOperationException("Missing required appSetting: PdfBasePath"); } if (!Directory.Exists(basePath)) { throw new InvalidOperationException($"Directory not found: {basePath}"); } string tempPath = Path.Combine(basePath, "temp"); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } string imagePath = Path.Combine(basePath, "images"); if (!Directory.Exists(imagePath)) { Directory.CreateDirectory(imagePath); } string template = Path.Combine(basePath, "IOFTemplate.pdf"); if (!File.Exists(template)) { throw new InvalidOperationException($"Missing template file: {template}"); } string templatePage2 = Path.Combine(basePath, "IOFTemplatePage2.pdf"); if (!File.Exists(templatePage2)) { throw new InvalidOperationException($"Missing template page 2 file: {templatePage2}"); } var c = ClientRepository.Single(po.ClientID); string pdfName = $"IOF_{po.POID}_{c.LName}{c.FName}_{DateTime.Now:yyMmddHHmmss}.pdf"; string pdfPath = Path.Combine(tempPath, pdfName); if (File.Exists(pdfPath)) { File.Delete(pdfPath); } using (var fs = new FileStream(pdfPath, FileMode.Create, FileAccess.Write)) { PdfReader pr = new PdfReader(template); PdfStamper ps = new PdfStamper(pr, fs); AcroFields af = ps.AcroFields; var info = pr.Info; info["Title"] = $"IOF #{po.POID} : {po.VendorName} : {c.FName} {c.LName}"; ps.MoreInfo = info; using (var ms = new MemoryStream()) { var xmp = new XmpWriter(ms, info); ps.XmpMetadata = ms.ToArray(); xmp.Close(); } af.SetField("poID", $"IOF # {po.POID}"); af.SetField("RequestedBy", c.DisplayName); af.SetField("Email", c.Email); af.SetField("Phone", c.Phone); var approver = ClientRepository.GetApprover(po); if (po.IsApproved()) { string imageFile = Path.Combine(imagePath, $"{approver.LName}.tif"); if (File.Exists(imageFile)) { var sig = Image.GetInstance(imageFile); ps.GetOverContent(1).AddImage(sig, 50, 0, 0, 24, 231, 539); } af.SetField("ApprovedBy", approver.DisplayName); } // fill in shipping info af.SetField("Date", po.CreatedDate.ToShortDateString()); af.SetField("DateNeeded", po.NeededDate.ToShortDateString()); af.SetField("Advisor", approver.DisplayName); af.SetField("Shipping", po.ShippingMethodName); var acct = AccountRepository.Single(po.ClientID, po.AccountID); if (acct == null) { af.SetField("Account", string.Empty); } else { af.SetField("Account", acct.ShortCode); } if (po.Oversized) { af.SetField("chkOverSized", "Yes"); } af.SetField("PurchaseTotal", po.TotalPrice.ToString("#,##0.00")); // fill in vendor info var vendor = VendorRepository.Single(po.VendorID); af.SetField("Vendor", vendor.VendorName); af.SetField("VendAddr1", vendor.Address1); af.SetField("VendAddr2", vendor.Address2); af.SetField("VendAddr3", vendor.Address3); af.SetField("Contact", vendor.Contact); af.SetField("ContactPhone", vendor.Phone); af.SetField("ContactFax", vendor.Fax); af.SetField("VendorWWW", vendor.URL); af.SetField("ContactEmail", vendor.Email); // in the 'office use only' box af.SetField("VendorOffice", vendor.VendorName); // notes var items = GetItems(po.POID).ToList(); if (!string.IsNullOrEmpty(po.Notes)) { items.Add(new PdfItem() { Description = po.Notes, IsNotes = true }); } // items int x = 0; float y = 410F; //page 1 starting position int pageNumber = 1; float width = pr.GetPageSize(pageNumber).Width - x; //DrawLine(ps.GetOverContent(page), 280) foreach (var item in items.OrderByDescending(i => i.PODID)) { var tbl = CreateTable(item, width); if (pageNumber < 2) { if (y + tbl.TotalHeight < 280) { pageNumber = 2; y = 580; //page 2 starting position ps.InsertPage(pageNumber, pr.GetPageSize(1)); var p2reader = new PdfReader(templatePage2); ps.ReplacePage(p2reader, 1, 2); ps.Writer.FreeReader(p2reader); p2reader.Close(); //DrawLine(ps.GetOverContent(page), 60) } } else { if (y + tbl.TotalHeight < 60) { pageNumber += 1; y = 580; //page n starting position ps.InsertPage(pageNumber, pr.GetPageSize(1)); var p2reader = new PdfReader(templatePage2); ps.ReplacePage(p2reader, 1, pageNumber); ps.Writer.FreeReader(p2reader); p2reader.Close(); //DrawLine(ps.GetOverContent(page), 60) } } var ct = new ColumnText(ps.GetOverContent(pageNumber)) { Alignment = Element.ALIGN_LEFT }; ct.SetSimpleColumn(x, y, width, y + 100); ct.AddElement(tbl); ct.Go(); y -= tbl.TotalHeight; } AddPageNumberFooter(ps, pr.NumberOfPages, width); ps.FormFlattening = true; ps.Close(); } return(pdfPath); }
/* * * Metoda odpowiedzialna za tworzenie faktury. */ public void Invoice() { var pokUserInfo = this._dataService.GetPokInformation(LoginForm.sendtext); string path = Directory.GetCurrentDirectory(); orderNr = this._dataService.GetTransactionId(); string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string now2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string now4 = DateTime.Now.ToString("yyyy/MM/dd"); string now5 = DateTime.Now.AddDays(10).ToString("yyyy-MM-dd HH:mm:ss"); iTextSharp.text.Font x = FontFactory.GetFont("HELVETICA_BOLD", 17); System.Windows.Shapes.Rectangle ee = new System.Windows.Shapes.Rectangle(); var pdfDoc = new Document(new iTextSharp.text.Rectangle(550f, 440f)); SaveFileDialog sfd = new SaveFileDialog(); sfd.FileName = desktop + "\\FV_" + pokUserInfo.FirstOrDefault().POK + "_" + orderNr + ".pdf"; sfd.Filter = "Pdf File |*.pdf"; if (sfd.ShowDialog() == DialogResult.OK && sfd.FileName != "") { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(sfd.FileName, FileMode.OpenOrCreate)); pdfDoc.Open(); //Ustwienie koloru Color myColor = Color.LightGray; string htmlColor = ColorTranslator.ToHtml(myColor); PdfPTable table = new PdfPTable(1); PdfPCell cell = new PdfPCell(new Paragraph("Faktura FV/" + pokUserInfo.FirstOrDefault().POK + "/" + now4, new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 14f))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); cell.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER; //| iTextSharp.text.Rectangle.TOP_BORDER; cell.BorderWidthBottom = 2f; cell.PaddingBottom = 5f; cell.PaddingLeft = 5f; table.WidthPercentage = 42; table.AddCell(cell); pdfDoc.Add(table); iTextSharp.text.Font f = new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 15f); Chunk c = new Chunk("Oryginał/Kopia", f); c.SetBackground(BaseColor.LIGHT_GRAY); PdfContentByte cb55 = writer.DirectContent; ColumnText ct2 = new ColumnText(cb55); ct2.SetSimpleColumn(new Phrase(c), 540, 415, 425, 22, 25, Element.ALIGN_RIGHT | Element.ALIGN_TOP); ct2.Go(); Chunk c1 = new Chunk("Nabywca: ", f); c1.SetBackground(BaseColor.LIGHT_GRAY); ct2.SetSimpleColumn(new Phrase(c1), 52, 305, 825, 22, 25, Element.ALIGN_LEFT | Element.ALIGN_TOP); ct2.Go(); Chunk c2 = new Chunk("Sprzedawca: ", f); c2.SetBackground(BaseColor.LIGHT_GRAY); ct2.SetSimpleColumn(new Phrase(c2), 272, 305, 825, 22, 25, Element.ALIGN_LEFT | Element.ALIGN_TOP); ct2.Go(); iTextSharp.text.Font f2 = new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f); Chunk c3 = new Chunk("Podpis osoby uprawnionej do wystawienia faktury", f2); c3.SetBackground(BaseColor.LIGHT_GRAY); ct2.SetSimpleColumn(new Phrase(c3), 52, 115, 429, 22, 25, Element.ALIGN_LEFT | Element.ALIGN_TOP); ct2.Go(); Chunk c4 = new Chunk("Podpis osoby uprawnionej do otrzymania faktury", f2); c4.SetBackground(BaseColor.LIGHT_GRAY); ct2.SetSimpleColumn(new Phrase(c4), 315, 115, 820, 22, 25, Element.ALIGN_RIGHT | Element.ALIGN_TOP); ct2.Go(); Chunk c5 = new Chunk("UWAGI:", f); c5.SetBackground(BaseColor.LIGHT_GRAY); ct2.SetSimpleColumn(new Phrase(c5), 22, 50, 140, 22, 25, Element.ALIGN_LEFT | Element.ALIGN_CENTER); ct2.Go(); PdfContentByte cb = writer.DirectContent; cb.SaveState(); cb.SetColorFill(BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 8f); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, komentarz, 138, 27, 0); //dane do faktury cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, clientName, 52, 255, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "ul. " + street, 52, 240, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, postal_code + " " + city, 52, 225, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Zarząd Transportu Miejskiego", 272, 255, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Dembowskiego 17", 272, 240, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "36-100 Kolbuszowa ", 272, 225, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, now2, 162, 345, 0); //data wystawienia cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, now5, 162, 325, 0); //termin zaplaty cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, now3, 352, 345, 0); //data sprzedazy cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "1 z 1", 322, 305, 0); //strona cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, nipTXT.Text, 93, 210, 0); //NIP nabywcy cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "00" + CLIENTID, 112, 195, 0); //ID klienta cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "2119743555", 309, 210, 0); //NIP sprzedawcy cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "359369141", 313, 195, 0); // REGON cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, pokUserInfo.FirstOrDefault().POK.ToString(), 310, 180, 0); //strona cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "12 1050 9870 1420 0023 4240 6432", 334, 165, 0); //strona if (this.CardBool == true) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Karta", 352, 325, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "0", 182, 305, 0); } else if (this.CashBool == true) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Gotówka", 352, 325, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "0", 182, 305, 0); } else if (transferBOOL == true) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Przelew bankowy", 352, 325, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "10", 182, 305, 0);//termin zaplaty w dniach } cb.EndText(); cb.RestoreState(); PdfContentByte cb3 = writer.DirectContent; cb3.SaveState(); cb3.SetColorFill(BaseColor.BLACK); cb3.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 9f); cb3.BeginText(); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ".............................................................................", 52, 60, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "...........................................................................", 503, 60, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_CENTER, pokUserInfo.FirstOrDefault().Name + " " + pokUserInfo.FirstOrDefault().Surname, 150, 67, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Data wystawienia: ", 52, 345, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Termin zapłaty: ", 52, 325, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Termin zapłaty (w dniach): ", 52, 305, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Data sprzedaży: ", 272, 345, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Typ płatności: ", 272, 325, 0); //dodac cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Strona: ", 272, 305, 0); //dodac cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "NIP: ", 52, 210, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "NIP: ", 272, 210, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Id klienta: ", 52, 195, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Regon: ", 272, 195, 0); cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "MPS: ", 272, 180, 0); //dodac cb3.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Numer konta: ", 272, 165, 0); //dodac cb3.EndText(); cb3.RestoreState(); PdfContentByte cb2 = writer.DirectContent; cb2.SetColorFill(BaseColor.BLACK); cb2.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 2f); PdfPTable table2 = new PdfPTable(8); table2.TotalWidth = 450f; //table2.WidthPercentage = 90f; int[] firstTablecellwidth = { 3, 6, 20, 8, 8, 8, 8, 8 }; table2.SetWidths(firstTablecellwidth); PdfPCell theCell = new PdfPCell(new Paragraph("Lp.", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 9f))); PdfPCell theCell2 = new PdfPCell(new Paragraph("Ilość", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f))); PdfPCell theCell3 = new PdfPCell(new Paragraph("Nazwa Towaru", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f))); PdfPCell theCell4 = new PdfPCell(new Paragraph("Id produktu", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f))); PdfPCell theCell5 = new PdfPCell(new Paragraph("Wartość netto", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f))); PdfPCell theCell6 = new PdfPCell(new Paragraph("Stawka VAT", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f))); PdfPCell theCell7 = new PdfPCell(new Paragraph("Kwota VAT", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f))); PdfPCell theCell8 = new PdfPCell(new Paragraph("Wartość brutto", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 8f))); PdfPCell odp1 = new PdfPCell(new Paragraph("1", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); PdfPCell odp2 = new PdfPCell(new Paragraph(this.Quantity, new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); PdfPCell odp3 = new PdfPCell(new Paragraph(this.productDesc, new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); PdfPCell odp4 = new PdfPCell(new Paragraph(this.PRODUCTID, new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); PdfPCell odp5 = new PdfPCell(new Paragraph(this.NETTO + "zł", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); PdfPCell odp6 = new PdfPCell(new Paragraph(this.VATAMOUNT + "%", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); PdfPCell odp7 = new PdfPCell(new Paragraph(this.VAT + "zł", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); PdfPCell odp8 = new PdfPCell(new Paragraph(this.BRUTTO + "zł", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 7f))); theCell.HorizontalAlignment = Element.ALIGN_CENTER; theCell2.HorizontalAlignment = Element.ALIGN_CENTER; theCell3.HorizontalAlignment = Element.ALIGN_CENTER; theCell4.HorizontalAlignment = Element.ALIGN_CENTER; theCell5.HorizontalAlignment = Element.ALIGN_CENTER; theCell6.HorizontalAlignment = Element.ALIGN_CENTER; theCell7.HorizontalAlignment = Element.ALIGN_CENTER; theCell8.HorizontalAlignment = Element.ALIGN_CENTER; odp1.HorizontalAlignment = Element.ALIGN_CENTER; odp2.HorizontalAlignment = Element.ALIGN_CENTER; odp3.HorizontalAlignment = Element.ALIGN_CENTER; odp4.HorizontalAlignment = Element.ALIGN_CENTER; odp5.HorizontalAlignment = Element.ALIGN_CENTER; odp6.HorizontalAlignment = Element.ALIGN_CENTER; odp7.HorizontalAlignment = Element.ALIGN_CENTER; odp8.HorizontalAlignment = Element.ALIGN_CENTER; theCell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); theCell2.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); theCell3.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); theCell4.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); theCell5.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); theCell6.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); theCell7.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); theCell8.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); table2.AddCell(theCell); table2.AddCell(theCell2); table2.AddCell(theCell3); table2.AddCell(theCell4); table2.AddCell(theCell5); table2.AddCell(theCell6); table2.AddCell(theCell7); table2.AddCell(theCell8); table2.AddCell(odp1); table2.AddCell(odp2); table2.AddCell(odp3); table2.AddCell(odp4); table2.AddCell(odp5); table2.AddCell(odp6); table2.AddCell(odp7); table2.AddCell(odp8); PdfPCell sumUP = new PdfPCell(new Paragraph("Razem:", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 10f))); PdfPCell sumUP2 = new PdfPCell(new Paragraph(BRUTTO + "zł", new iTextSharp.text.Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 9f))); sumUP2.HorizontalAlignment = Element.ALIGN_RIGHT; sumUP.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml(htmlColor)); PdfPTable nested = new PdfPTable(2); nested.TotalWidth = 450f; int[] firstTablecellwidth2 = { 13, 18 }; nested.SetWidths(firstTablecellwidth2); nested.AddCell(sumUP); nested.AddCell(sumUP2); nested.WriteSelectedRows(0, -1, 52, 127, cb2); table2.WriteSelectedRows(0, -1, 52, 158, cb2); pdfDoc.Close(); } }
/* a method that save the packing slip pdf */ public static void CreatePackingSlip(GiantTigerValues value, int[] cancelIndex, bool preview) { // the case if all of the items in the order are cancelled -> don't need to print the packing slip if (cancelIndex.Length >= value.VendorSku.Count) { return; } // first check if the save directory exist -> if not create it if (!File.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } // initialize fields Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0); string file = SavePath + "\\" + value.PoNumber + ".pdf"; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(file, FileMode.Create)); // open the documents doc.Open(); PdfContentByte contentByte = writer.DirectContent; PdfContentByte draw = writer.DirectContent; #region Logo and Barcode Set Up // add giant tiger logo Image logo = Image.GetInstance(Properties.Resources.giantTigerPackSlip, System.Drawing.Imaging.ImageFormat.Png); logo.ScalePercent(20f); logo.SetAbsolutePosition(40f, doc.PageSize.Height - 100f); doc.Add(logo); // add barcode Barcode39 barcode39 = new Barcode39 { Code = value.OmsOrderNumber, StartStopText = false, Font = null, Extended = true }; Image image = barcode39.CreateImageWithBarcode(contentByte, BaseColor.BLACK, BaseColor.BLACK); image.ScaleAbsoluteHeight(40f); image.SetAbsolutePosition(340f, doc.PageSize.Height - 80f); contentByte.AddImage(image); #endregion // initialize local fields for text BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); BaseFont boldFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false); CMYKColor white = new CMYKColor(0f, 0f, 0f, 0f); CMYKColor black = new CMYKColor(0f, 0f, 0f, 1f); ColumnText ct = new ColumnText(draw); #region Sold To // sold to Phrase text = new Phrase("SOLD TO / VENDU A", new Font(boldFont, 10)); ct.SetSimpleColumn(text, 40f, 655f, 200f, 670f, 0f, Element.ALIGN_LEFT); ct.Go(); // sold to address text = new Phrase(value.ShipTo.Name + '\n' + value.ShipTo.Address1 + '\n' + value.ShipTo.Address2 + '\n' + value.ShipTo.City + ", " + value.ShipTo.State + ' ' + value.ShipTo.PostalCode + "\nCanada", new Font(baseFont, 9)); ct.SetSimpleColumn(text, 42f, 568f, 177f, 668f, 10f, Element.ALIGN_LEFT); ct.Go(); #endregion #region Ship To // ship to text = new Phrase("SHIP TO / EXPEDIE A", new Font(boldFont, 10f)); ct.SetSimpleColumn(text, 300f, 655f, 450f, 670f, 0f, Element.ALIGN_LEFT); ct.Go(); // ship to address text = new Phrase(value.ShipTo.Name + '\n' + value.ShipTo.Address1 + '\n' + value.ShipTo.Address2 + '\n' + value.ShipTo.City + ", " + value.ShipTo.State + ' ' + value.ShipTo.PostalCode + "\nCanada\n" + value.ShipTo.DayPhone, new Font(baseFont, 9f)); ct.SetSimpleColumn(text, 302f, 568f, 447f, 668f, 10f, Element.ALIGN_LEFT); ct.Go(); #endregion #region Draw First Box draw.SetColorFill(black); draw.MoveTo(40f, 580f); draw.LineTo(doc.PageSize.Width - 40f, 580f); draw.LineTo(doc.PageSize.Width - 40f, 543f); draw.LineTo(40f, 543f); draw.LineTo(40f, 580f); draw.ClosePathFillStroke(); draw.SetColorStroke(white); draw.MoveTo(160f, 580f); draw.LineTo(160f, 543f); draw.Stroke(); draw.MoveTo(280f, 580f); draw.LineTo(280f, 543f); draw.Stroke(); draw.MoveTo(320f, 580f); draw.LineTo(320f, 543f); draw.Stroke(); draw.MoveTo(500f, 580f); draw.LineTo(500f, 543f); draw.Stroke(); draw.SetColorStroke(black); draw.MoveTo(40f, 543f); draw.LineTo(40f, 530f); draw.Stroke(); draw.MoveTo(40f, 530f); draw.LineTo(doc.PageSize.Width - 40f, 530f); draw.Stroke(); draw.MoveTo(doc.PageSize.Width - 40f, 530f); draw.LineTo(doc.PageSize.Width - 40f, 543f); draw.Stroke(); draw.MoveTo(160f, 543f); draw.LineTo(160f, 530f); draw.Stroke(); draw.MoveTo(280f, 543f); draw.LineTo(280f, 530f); draw.Stroke(); draw.MoveTo(320f, 543f); draw.LineTo(320f, 530f); draw.Stroke(); draw.MoveTo(500f, 543f); draw.LineTo(500f, 530f); draw.Stroke(); #endregion #region Messgae in First Box text = new Phrase("SHIPPING METHOD \\\nMODE D'EXPEDITION", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 40f, 550f, 160f, 580f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("ORDER DATE \\\nDATE DE LA\nCOMMANDE", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 160f, 540f, 280f, 580f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("PAGE", new Font(boldFont, 10, Font.NORMAL, new CMYKColor(0f, 0f, 0f, 0f))); ct.SetSimpleColumn(text, 280f, 550f, 320f, 580f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("ORDER NUMBER \\\nNUMERO DE COMMANDE", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 320f, 550f, 500f, 580f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("PO NUMBER \\\nBON DE\nCOMMANDE", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 500f, 540f, doc.PageSize.Width - 40f, 580f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("Canada Post Ground", new Font(baseFont, 10)); ct.SetSimpleColumn(text, 40f, 523f, 160f, 533f, 0f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase(value.OrderDate.ToString("MM/dd/yyyy"), new Font(baseFont, 10)); ct.SetSimpleColumn(text, 160f, 523f, 280f, 533f, 0f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("1 of 1", new Font(baseFont, 10)); ct.SetSimpleColumn(text, 280f, 523f, 320f, 533f, 0f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase(value.WebOrderNo, new Font(baseFont, 10)); ct.SetSimpleColumn(text, 320f, 523f, 500f, 533f, 0f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase(value.PoNumber, new Font(baseFont, 10)); ct.SetSimpleColumn(text, 500f, 523f, doc.PageSize.Width - 40f, 533f, 0f, Element.ALIGN_CENTER); ct.Go(); #endregion #region Draw Second Box draw.MoveTo(40f, 520f); draw.LineTo(doc.PageSize.Width - 40f, 520f); draw.LineTo(doc.PageSize.Width - 40f, 483f); draw.LineTo(40f, 483f); draw.LineTo(40f, 520f); draw.ClosePathFillStroke(); draw.SetColorStroke(white); draw.MoveTo(130f, 520f); draw.LineTo(130f, 483f); draw.Stroke(); draw.MoveTo(220f, 520f); draw.LineTo(220f, 483f); draw.Stroke(); draw.MoveTo(400f, 520f); draw.LineTo(400f, 483f); draw.Stroke(); draw.MoveTo(480f, 520f); draw.LineTo(480f, 483f); draw.Stroke(); #endregion #region Message in Second Box text = new Phrase("QTY ORDERED \\\nQTE\nCOMMANDEE", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 40f, 480f, 130f, 520f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("ITEM \\\nARTICLE", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 130f, 480f, 220f, 520f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("DESCRIPTION", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 220f, 480f, 400f, 520f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("QTY SHIPPED \\\nQTE EXPEDIEE", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 400f, 480f, 480f, 520f, 11f, Element.ALIGN_CENTER); ct.Go(); text = new Phrase("VENDOR SKU \\\nNO D'ARTICLE DU\nFOURNISSEUR", new Font(boldFont, 10, Font.NORMAL, white)); ct.SetSimpleColumn(text, 480f, 480f, doc.PageSize.Width - 40f, 520f, 11f, Element.ALIGN_CENTER); ct.Go(); // item addition draw.SetColorStroke(black); draw.SetLineWidth(0.25f); float height = 480f; // adding items for (int i = 0; i < value.VendorSku.Count; i++) { // if the item is cancelled, skip this item if (cancelIndex.Any(j => i == j)) { continue; } // draw box draw.MoveTo(40f, height); draw.LineTo(40f, height - 10f); draw.Stroke(); draw.MoveTo(40f, height - 10f); draw.LineTo(doc.PageSize.Width - 40f, height - 10f); draw.Stroke(); draw.MoveTo(doc.PageSize.Width - 40f, height - 10f); draw.LineTo(doc.PageSize.Width - 40f, height); draw.Stroke(); draw.MoveTo(130f, height); draw.LineTo(130f, height - 10f); draw.Stroke(); draw.MoveTo(220f, height); draw.LineTo(220f, height - 10f); draw.Stroke(); draw.MoveTo(400f, height); draw.LineTo(400f, height - 10f); draw.Stroke(); draw.MoveTo(480f, height); draw.LineTo(480f, height - 10f); draw.Stroke(); // qty text = new Phrase(value.Quantity[i].ToString(), new Font(baseFont, 10)); ct.SetSimpleColumn(text, 40f, height - 19f, 130, height - 9f, 0f, Element.ALIGN_CENTER); ct.Go(); // item text = new Phrase(value.ClientItemId[i], new Font(baseFont, 10)); ct.SetSimpleColumn(text, 130f, height - 19f, 220f, height - 9f, 0f, Element.ALIGN_CENTER); ct.Go(); // description text = new Phrase("", new Font(baseFont, 10)); ct.SetSimpleColumn(text, 220f, height - 19f, 400f, height - 9f, 0f, Element.ALIGN_CENTER); ct.Go(); // qty shipped text = new Phrase(value.Quantity[i].ToString(), new Font(baseFont, 10)); ct.SetSimpleColumn(text, 400f, height - 19f, 480f, height - 9f, 0f, Element.ALIGN_CENTER); ct.Go(); // vendor sku text = new Phrase(value.VendorSku[i], new Font(baseFont, 10)); ct.SetSimpleColumn(text, 480f, height - 19f, doc.PageSize.Width - 40f, height - 9f, 0f, Element.ALIGN_CENTER); ct.Go(); // decrease height for next item height -= 10f; } #endregion #region Ending Boxes #region Top Box // restore width draw.SetLineWidth(1f); // draw box draw.MoveTo(40f, 250f); draw.LineTo(doc.PageSize.Width - 40f, 250f); draw.LineTo(doc.PageSize.Width - 40f, 235f); draw.LineTo(40f, 235f); draw.LineTo(40f, 250f); draw.ClosePathFillStroke(); // message in the box text = new Phrase("Thank you for ordering from Giant Tiger! Merci d’avoir placé une commande chez Tigre Géant!", new Font(boldFont, 10f, Font.NORMAL, white)); ct.SetSimpleColumn(text, 40f, 224f, doc.PageSize.Width - 40f, 239f, 0f, Element.ALIGN_CENTER); ct.Go(); #endregion #region Bottom Box // draw box draw.MoveTo(40f, 225f); draw.LineTo(doc.PageSize.Width - 40f, 225f); draw.Stroke(); draw.MoveTo(doc.PageSize.Width - 40f, 225f); draw.LineTo(doc.PageSize.Width - 40f, 50f); draw.Stroke(); draw.MoveTo(doc.PageSize.Width - 40f, 50f); draw.LineTo(40f, 50f); draw.Stroke(); draw.MoveTo(40f, 50f); draw.LineTo(40f, 225f); draw.Stroke(); draw.MoveTo(doc.PageSize.Width / 2, 225f); draw.LineTo(doc.PageSize.Width / 2, 50f); draw.Stroke(); // message in the left box text = new Phrase("Didn't receive your entire order or questions about your order?\n" + "You may receive your order in separate shipments. To track your order status. Please log into My Account at gianttiger.com.\n\r" + "Want to Return or Exchange an Item?\n" + "If you are not satisfied with your order for any reason please contact our Customer Service Team at 1-844-99-GIANT (44268) or email [email protected]. " + "For in-store returns or exchanges, your shipment confirmation email is required. To review our return policy, please visit gianttiger.com/ReturnPolicy.", new Font(baseFont, 9f)); ct.SetSimpleColumn(text, 50f, 55f, doc.PageSize.Width / 2 - 10, 225f, 10f, Element.ALIGN_LEFT); ct.Go(); // message in the right box text = new Phrase("Votre commande est incomplète ou vous avez des questions à son sujet?\n" + "Il se peut que vous receviez votre commande dans des envois distincts. Pour suivre l'état de votre commande, s’il vous plaît vous connecter à Mon Compte au tigregeant.com.\n\r" + "Vous voulez retourner ou échanger un article?\nSi vous n'êtes pas satisfait avec votre achat, veuillez communiquer avec notre service à la clientèle au 1-844-99-GIANT (44268) " + "ou envoyer un courriel à [email protected]. Les échanges et les remboursements peuvent être effectués à n’importe quel de nos magasins avec la présentation du courriel confirmant " + "l'expédition de votre commande. Pour consulter notre politique de retour, s'il vous plaît visitez tigregeant.com/PolitiqueRetour.", new Font(baseFont, 9f)); ct.SetSimpleColumn(text, doc.PageSize.Width / 2 + 10f, 55f, doc.PageSize.Width - 50f, 225f, 10f, Element.ALIGN_LEFT); ct.Go(); #endregion #endregion doc.Close(); if (!preview) { return; } // start the pdf for previewing if (System.Diagnostics.Process.GetProcessesByName(file).Length < 1) { System.Diagnostics.Process.Start(file); } }
protected override void CreateKFactorLabel(PDFDocument document, TachographDocument tachographDocument) { ColumnText kValueColumn = document.GetNewColumn(425, document.Height - 356, 480, 100); document.AddParagraph(tachographDocument.KFactor, kValueColumn); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; CmsData.Meeting meeting = null; if (meetingid.HasValue) { meeting = DbUtil.Db.Meetings.Single(mt => mt.MeetingId == meetingid); dt = meeting.MeetingDate; orgid = meeting.OrganizationId; } var list1 = bygroup == true?ReportList2().ToList() : ReportList().ToList(); if (!list1.Any()) { Response.Write("no data found"); return; } if (!dt.HasValue) { Response.Write("bad date"); return; } Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "filename=foo.pdf"); doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64); var w = PdfWriter.GetInstance(doc, Response.OutputStream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; box = new PdfPCell(); box.Border = PdfPCell.NO_BORDER; box.CellEvent = new CellEvent(); PdfPTable table = null; OrgInfo lasto = null; foreach (var o in list1) { lasto = o; table = new PdfPTable(1); table.DefaultCell.Border = PdfPCell.NO_BORDER; table.DefaultCell.Padding = 0; table.WidthPercentage = 100; if (meeting != null) { var Groups = o.Groups; if (Groups[0] == 0) { var q = from at in meeting.Attends where at.AttendanceFlag == true || at.Commitment == AttendCommitmentCode.Attending || at.Commitment == AttendCommitmentCode.Substitute orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new { at.MemberType.Code, Name2 = (altnames == true && at.Person.AltName != null && at.Person.AltName.Length > 0) ? at.Person.AltName : at.Person.Name2, at.PeopleId, at.Person.DOB, }; if (q.Any()) { StartPageSet(o); } foreach (var a in q) { table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font)); } } else { var q = from at in meeting.Attends let om = at.Organization.OrganizationMembers.SingleOrDefault(mm => mm.PeopleId == at.PeopleId) let gc = om.OrgMemMemTags.Count(mt => Groups.Contains(mt.MemberTagId)) where gc == Groups.Length || Groups[0] <= 0 where gc > 0 where !Groups.Contains(-1) || (Groups.Contains(-1) && om.OrgMemMemTags.Count() == 0) where at.AttendanceFlag == true || at.Commitment == AttendCommitmentCode.Attending || at.Commitment == AttendCommitmentCode.Substitute orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new { at.MemberType.Code, Name2 = (altnames == true && at.Person.AltName != null && at.Person.AltName.Length > 0) ? at.Person.AltName : at.Person.Name2, at.PeopleId, at.Person.DOB, }; if (q.Any()) { StartPageSet(o); } foreach (var a in q) { table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font)); } } } else { var Groups = o.Groups; if (Groups == null) { Groups = new int[] { 0 } } ; var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == o.OrgId let gc = om.OrgMemMemTags.Count(mt => Groups.Contains(mt.MemberTagId)) where gc == Groups.Length || Groups[0] <= 0 where !Groups.Contains(-1) || (Groups.Contains(-1) && om.OrgMemMemTags.Count() == 0) where (om.Pending ?? false) == false where om.MemberTypeId != MemberTypeCode.InActive where om.MemberTypeId != MemberTypeCode.Prospect where om.EnrollmentDate <= Util.Now orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = altnames == true && p.AltName != null && p.AltName.Length > 0 select new { PeopleId = p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Util.FormatBirthday( p.BirthYear, p.BirthMonth, p.BirthDay), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == highlightsg) ? highlightsg : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china : font)); } } if (bygroup == false && groups[0] == 0 && meeting == null) { foreach (var m in RollsheetModel.FetchVisitors(o.OrgId, dt.Value, NoCurrentMembers: true, UseAltNames: altnames == true)) { if (table.Rows.Count == 0) { StartPageSet(o); } table.AddCell(AddRow(m.VisitorType, m.Name2, m.PeopleId, m.BirthDate, "", boldfont)); } } if (!pageSetStarted) { continue; } var col = 0; float gutter = 20f; float colwidth = (doc.Right - doc.Left - gutter) / 2; var ct = new ColumnText(w.DirectContent); ct.AddElement(table); int status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, doc.Top); } else { ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, doc.Top); } status = ct.Go(); ++col; if (col > 1) { col = 0; doc.NewPage(); } } // foreach (var li in list) // { // y = ct.YLine; // ct.AddElement(li); // status = ct.Go(true); // if (ColumnText.HasMoreText(status)) // { // ++col; // if (col > 1) // { // col = 0; // doc.NewPage(); // } // ct.SetSimpleColumn(cols[col]); // y = doc.Top; // } // ct.YLine = y; // ct.SetText(null); // ct.AddElement(li); // status = ct.Go(); // } } if (!hasRows) { if (!pageSetStarted) { StartPageSet(lasto); } doc.Add(new Paragraph("no members as of this meeting date and time to show on rollsheet")); } doc.Close(); }
private void GenerateReport() { //string z nazwą pomieszczenia string fileName = ""; fileName = "Wykaz sprzętu"; //ścieżka z nazwą pliku do tworzenia string path = Application.StartupPath + "/Wydruki sprzętu/" + fileName + ".pdf"; //ścieżka do utworzenia katalogu na wydruki string path2 = Application.StartupPath + "/Wydruki sprzętu/"; //ustawienie zabezpieczenia do zapisu i tworzenie katalogu DirectorySecurity securityRules = new DirectorySecurity(); string dirPath = Path.GetDirectoryName(path2); securityRules.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Modify, AccessControlType.Allow)); if (dirPath == null) { throw new InvalidOperationException("Nie udało się zapisać ze względu na lokalne ustawienia bezpieczeństwa!"); } if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath, securityRules); } //rozmiar dokumentu i marginesów Document document = new Document(PageSize.A4.Rotate(), 25, 25, 50, 50); //ustawienia czcionek var bigFont = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 18); var normalFont = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 10); var smallFont = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 4); //utworzenie dokumentu PdfWriter writer = null; bool bOpen = false; try { writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create)); //ewent do numeracji stron writer.PageEvent = new ITextEvent(); } catch (IOException e) { MessageBox.Show(e.Message, "OSTRZEŻENIE!", MessageBoxButtons.OK, MessageBoxIcon.Warning); bOpen = true; } if (bOpen == false) { document.Open(); //treść wydruku //tutuł Paragraph p = new Paragraph("Spis sprzętu Informatyki i Łączności:" + Environment.NewLine, bigFont); p.Alignment = Element.ALIGN_CENTER; document.Add(p); p = new Paragraph(Environment.NewLine, bigFont); p.Alignment = Element.ALIGN_CENTER; document.Add(p); //tabela z datagridview int iloscKolumn = 0; for (int i = 0; i < dataGridView1.Columns.Count; i++) { if (dataGridView1.Columns[i].Visible == true) { iloscKolumn++; } } PdfPTable pdfTable = new PdfPTable(iloscKolumn); //dataGridView1.Columns.Count); //rozmiar szerokosc kolumn float[] widths = new float[] { 50f, 100f, 105f, 150f, 80f, 80f, 100f, 100f, 100f, 100f, 85f, 100f, 100f, 100f, 100f, 110f, 110f, 150f, 100f, 100f, 100f, 100f, 100f, 150f, 165f, 110f, 100f, 150f }; //zmienna do zapisu szerokosci kolumn wybranych kolumn float[] widths2 = new float[iloscKolumn]; int iWidths2 = 0; for (int i = 0; i < dataGridView1.Columns.Count; i++) { if (dataGridView1.Columns[i].Visible) { widths2[iWidths2] = widths[i]; iWidths2++; } } pdfTable.SetWidths(widths2); pdfTable.DefaultCell.Padding = 5; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; //tworzenie header column foreach (DataGridViewColumn column in dataGridView1.Columns) { if (column.Visible == true) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, smallFont)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_MIDDLE; pdfTable.AddCell(cell); } } //wypełnianie komorek danymi foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.Visible == true) { PdfPCell cell2 = new PdfPCell(new Phrase(cell.Value.ToString(), smallFont)); cell2.VerticalAlignment = Element.ALIGN_MIDDLE; pdfTable.AddCell(cell2); } } } document.Add(pdfTable); //dolne wpisy ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase("Wykaz sprzętu wygenerowany z EwiInf dla Aresztu Śledczego w Łodzi " + DateTime.Now.ToString(), normalFont), 250, 60, 0); //koniec wydruku document.Close(); //otwarcie pliku w pdf readerze Process.Start(path); } }
virtual public void TabColumnTextTest() { Font f = FontFactory.GetFont(FontFactory.COURIER, 11); Document doc = new Document(); Paragraph p; FileStream fs = new FileStream(OUTABC, FileMode.Create); PdfWriter writer = PdfWriter.GetInstance(doc, fs); writer.CompressionLevel = 0; doc.Open(); ColumnText ct = new ColumnText(writer.DirectContent); ct.SetSimpleColumn(36, 36, 436, 800); List <TabStop> tabStopsList = new List <TabStop>(); tabStopsList.Add(new TabStop(100, new DottedLineSeparator())); tabStopsList.Add(new TabStop(200, new LineSeparator(), TabStop.Alignment.CENTER)); tabStopsList.Add(new TabStop(300, new DottedLineSeparator(), TabStop.Alignment.RIGHT)); p = new Paragraph(new Chunk("Hello world", f)); p.TabSettings = new TabSettings(tabStopsList, 50); AddTabs(p, f, 0, "la|la"); ct.AddElement(p); tabStopsList = new List <TabStop>(); tabStopsList.Add(new TabStop(100, new DottedLineSeparator())); tabStopsList.Add(new TabStop(200, new LineSeparator(), TabStop.Alignment.ANCHOR)); tabStopsList.Add(new TabStop(300, new DottedLineSeparator(), TabStop.Alignment.ANCHOR)); p = new Paragraph(new Chunk("Hello World!!!")); p.TabSettings = new TabSettings(tabStopsList, 50); AddTabs(p, f, 12, "l.aal"); AddTabs(p, f, 12, "laa.l"); AddTabs(p, f, 12, "la.al"); ct.AddElement(p); f.Size = 16; p = new Paragraph(new Chunk("Hello world", f)); tabStopsList = new List <TabStop>(); tabStopsList.Add(new TabStop(100, new DottedLineSeparator())); tabStopsList.Add(new TabStop(200, new LineSeparator(), TabStop.Alignment.ANCHOR, ',')); tabStopsList.Add(new TabStop(300, new DottedLineSeparator(), TabStop.Alignment.ANCHOR)); p.TabSettings = new TabSettings(tabStopsList, 50); AddTabs(p, f, 15, "l.aal"); AddTabs(p, f, 13, "laa,l"); AddTabs(p, f, 13, "laa.l"); AddTabs(p, f, 13, "l,aal"); ct.AddElement(p); f = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12); p = new Paragraph(new Chunk("Hello world", f)); p.TabSettings = new TabSettings(38); AddTabs(p, f, 0); ct.AddElement(p); f.Size = 20; p = new Paragraph(new Chunk("Hello world", f)); p.TabSettings = new TabSettings(38); AddTabs(p, f, 0); ct.AddElement(p); ct.Go(); doc.Close(); fs.Close(); Assert.IsTrue(CompareInnerText(SOURCE14, OUTABC)); }
//generuje naklejki z qr code i nr ewidencyjnym do obklejenia private void GenerateQRAndEwi() { //string z nazwą pomieszczenia string fileName = ""; fileName = "Naklejki"; //ścieżka z nazwą pliku do tworzenia string path = Application.StartupPath + "/Naklejki/" + fileName + ".pdf"; //ścieżka do utworzenia katalogu na wydruki string path2 = Application.StartupPath + "/Naklejki/"; //ustawienie zabezpieczenia do zapisu i tworzenie katalogu DirectorySecurity securityRules = new DirectorySecurity(); string dirPath = Path.GetDirectoryName(path2); securityRules.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Modify, AccessControlType.Allow)); if (dirPath == null) { throw new InvalidOperationException("Nie udało się zapisać ze względu na lokalne ustawienia bezpieczeństwa!"); } if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath, securityRules); } //rozmiar dokumentu i marginesów Document document = new Document(PageSize.A4, 30, 30, 50, 50); //ustawienia czcionek var bigFont = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 18); var bigBoldFont = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.EMBEDDED, 18); var normalBoldFont = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.EMBEDDED, 14); var normalsmallFont = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 10); var smallFont = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 4); //utworzenie dokumentu PdfWriter writer = null; bool bOpen = false; try { writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create)); //ewent do numeracji stron //writer.PageEvent = new ITextEvent(); } catch (IOException e) { MessageBox.Show(e.Message, "OSTRZEŻENIE!", MessageBoxButtons.OK, MessageBoxIcon.Warning); bOpen = true; } if (bOpen == false) { document.Open(); //treść wydruku //generujemy naklejki PdfContentByte cb = writer.DirectContent; int xPoz = 45; int yPoz = 800; int xPio = 45; int yPio = 800; string s = ""; for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (i > 0) { if (i % 3 == 0) { yPoz = yPoz - 150; yPio = yPio - 150; xPoz = 45; xPio = 45; } } if (i < 30) { //linia pozioma cb.SetLineWidth(1); cb.MoveTo(xPoz, yPoz); cb.LineTo(xPoz + 170, yPoz); cb.Stroke(); cb.SetLineWidth(1); cb.MoveTo(xPoz, yPoz - 150); cb.LineTo(xPoz + 170, yPoz - 150); cb.Stroke(); //linia pionowa cb.SetLineWidth(1); cb.MoveTo(xPio, yPio); cb.LineTo(xPio, yPio - 150); cb.Stroke(); cb.SetLineWidth(1); cb.MoveTo(xPio + 170, yPio); cb.LineTo(xPio + 170, yPio - 150); cb.Stroke(); //numer ewidencyjny s = dataGridView1.Rows[i].Cells[1].Value.ToString().Trim(); ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(s, normalBoldFont), (xPoz) + (170 / 2), yPoz - 20, 0); //qrcode GenerateQR(dataGridView1.Rows[i].Cells[1].Value.ToString(), dataGridView1.Rows[i].Cells[3].Value.ToString(), dataGridView1.Rows[i].Cells[9].Value.ToString(), dataGridView1.Rows[i].Cells[24].Value.ToString(), dataGridView1.Rows[i].Cells[10].Value.ToString()); iTextSharp.text.Image qr = iTextSharp.text.Image.GetInstance(pbQRCode.BackgroundImage, System.Drawing.Imaging.ImageFormat.Jpeg); qr.ScaleAbsolute(100, 100); qr.SetAbsolutePosition(xPoz + 35, yPoz - 140); document.Add(qr); //cienka pozioma linia cb.SetLineWidth(0.25); cb.MoveTo(xPoz, yPoz - 30); cb.LineTo(xPoz + 170, yPoz - 30); cb.Stroke(); xPoz = xPoz + 170; xPio = xPio + 170; } } document.Close(); //otwarcie pliku w pdf readerze Process.Start(path); } }
public byte[] CreatePdf(Trip trip) { MemoryStream ms = new MemoryStream(); Document document = new Document(); var pdfwriter = PdfWriter.GetInstance(document, ms); document.Open(); PdfContentByte cb = pdfwriter.DirectContent; Paragraph companyName = new Paragraph(new Phrase("Tieto Czech s.r.o.")) { Font = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, false)), Alignment = Element.ALIGN_LEFT }; byte[] image = File.ReadAllBytes(Path.GetFullPath("~/../Assets/logo.png").Replace("~\\", "")); Image logo = Image.GetInstance(image); float logoWidth = 80; float logoHeight = (float)(80 / 2.97897898); logo.SetAbsolutePosition(document.Right - logoWidth, document.Top - logoHeight); logo.ScaleAbsolute(logoWidth, logoHeight); document.Add(companyName); document.Add(logo); ColumnText ct = new ColumnText(cb); string[] texts = { "Regulation - Appendix 1", "Reimbursement of traveling expenses - order", "V 2019_02.0", "Internal", "2019-03-12" }; for (int i = 0; i < 5; i++) { Paragraph p = new Paragraph(new Phrase(texts[i])) { Font = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, false), Font.DEFAULTSIZE - 2, i == 0 ? Font.BOLD : Font.NORMAL), Alignment = Element.ALIGN_LEFT }; ct.AddElement(p); } ct.SetSimpleColumn(document.Right / 2 - 80, document.Top, document.Right / 2 + 160, document.Top - 100); ct.Go(); cb.MoveTo(document.Left, document.Top - 100); cb.LineTo(document.Right, document.Top - 100); cb.Stroke(); Font headerTitleFont = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, false), Font.DEFAULTSIZE - 3, Font.NORMAL); Font headerContentFont = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, false), Font.DEFAULTSIZE - 3, Font.BOLD); Font headerContentFontItalic = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, false), Font.DEFAULTSIZE - 3, Font.ITALIC); PdfPTable headerTable = new PdfPTable(4); headerTable.SetWidths(new float[] { 1.5f, 1.0f, 0.7f, 0.8f }); headerTable.TotalWidth = document.Right - document.Left; headerTable.AddCell(new PdfPCell(new Phrase("Tieto Czech s.r.o.")) { Colspan = 1, Border = PdfPCell.BOTTOM_BORDER, PaddingBottom = 10f, PaddingLeft = 0f, BorderWidthBottom = 1f }); headerTable.AddCell(new PdfPCell(new Phrase("Business Trip Order", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, false), Font.DEFAULTSIZE + 2, Font.BOLD))) { Colspan = 3, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, Border = PdfPCell.BOTTOM_BORDER, PaddingBottom = 10f, PaddingRight = 0f, BorderWidthBottom = 1f }); headerTable.AddCell(new PdfPCell(new Phrase("Surname, Name, Title:", headerTitleFont)) { Border = PdfPCell.NO_BORDER, PaddingLeft = 0f, PaddingTop = 10f }); headerTable.AddCell(new PdfPCell(new Phrase("Name Surname", headerContentFont)) { Border = PdfPCell.NO_BORDER, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, PaddingTop = 10f, PaddingRight = 0f }); headerTable.AddCell(new PdfPCell(new Phrase("Project:", headerTitleFont)) { Border = PdfPCell.NO_BORDER, PaddingTop = 10f, PaddingLeft = 20f }); headerTable.AddCell(new PdfPCell(new Phrase(trip.Project, headerContentFont)) { Border = PdfPCell.NO_BORDER, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, PaddingRight = 0, PaddingTop = 10f }); headerTable.AddCell(new PdfPCell(new Phrase("Date and signature of employee's superior:", headerTitleFont)) { Border = PdfPCell.NO_BORDER, PaddingLeft = 0f }); headerTable.AddCell(new PdfPCell(new Phrase("") /*Replace with field*/) { Border = PdfPCell.BOTTOM_BORDER, BorderWidthBottom = 1f, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, PaddingRight = 0f }); headerTable.AddCell(new PdfPCell(new Phrase("Task:", headerTitleFont)) { Border = PdfPCell.NO_BORDER, PaddingLeft = 20f }); headerTable.AddCell(new PdfPCell(new Phrase(trip.Task, headerContentFont)) { Border = PdfPCell.NO_BORDER, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, PaddingRight = 0 }); headerTable.AddCell(new PdfPCell(new Phrase("Purpose of the trip:", headerTitleFont)) { Border = PdfPCell.NO_BORDER, PaddingLeft = 0f }); headerTable.AddCell(new PdfPCell(new Phrase(trip.Purpose, headerContentFont)) { Border = PdfPCell.NO_BORDER, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, PaddingRight = 0f }); headerTable.AddCell(new PdfPCell(new Phrase("Comment:", headerTitleFont)) { Border = PdfPCell.NO_BORDER, PaddingLeft = 20f }); headerTable.AddCell(new PdfPCell(new Phrase(trip.Comment != null && trip.Comment != "" ? trip.Comment : "No comment", trip.Comment != null && trip.Comment != "" ? headerContentFont : headerContentFontItalic)) { Border = PdfPCell.NO_BORDER, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, PaddingRight = 0 }); headerTable.WriteSelectedRows(0, 9, document.Left, document.Top - 105, cb); document.Close(); ms.Close(); byte[] pdf = ms.ToArray(); return(pdf); }
public void convertoonepdf(String Idproofimage, String resiproofimage, string documentproof, String VC, string PDFName, String Ecafno) { try { var creatfpdf = Server.MapPath("~/MyExcelFile/"); var finalPDF = System.IO.Path.Combine(creatfpdf, PDFName); var Header_text = getheader_text(); //This variable will eventually hold our combined PDF as a byte array Byte[] finalFileBytes; //Write everything to a MemoryStream using (var finalFile = new System.IO.MemoryStream()) { //Create a generic Document Document doc = new Document(); //Use PdfSmartCopy to intelligently merge files PdfSmartCopy copy = new PdfSmartCopy(doc, finalFile); //Open our document for writing doc.Open(); //#1 - Import the SSRS report //Bind a reader to our SSRS report PdfReader.unethicalreading = true; if (Idproofimage != "http://localhost/yesbank/MobImages/") { if (Idproofimage.ToUpper().Contains(".PDF")) { try { PdfReader reader1 = new PdfReader(Idproofimage); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); } catch { } } else { try { iTextSharp.text.Rectangle pageSize = null; WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(Idproofimage); MemoryStream ms = new MemoryStream(bytes); using (var srcImage = new Bitmap(ms)) { if (srcImage.Width < 580) { pageSize = new iTextSharp.text.Rectangle(0, 0, 580, srcImage.Height + 100); } else { pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height + 100); } } //Will eventually hold the PDF with the image as a byte array Byte[] imageBytes; //Simple image to PDF using (var m = new MemoryStream()) { Document d = new Document(pageSize, 0, 0, 0, 0); PdfWriter w = PdfWriter.GetInstance(d, m); d.Open(); d.Add(iTextSharp.text.Image.GetInstance(Idproofimage)); d.Close(); //Grab the bytes before closing out the stream imageBytes = m.ToArray(); } //Now merge using the same merge code as #1 PdfReader reader1 = new PdfReader(imageBytes); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); ms.Close(); } catch { } } } //#3 - Merge additional PDF if (resiproofimage != "http://localhost/yesbank/MobImages/") { if (resiproofimage.ToUpper().Contains(".PDF")) { try { PdfReader reader1 = new PdfReader(resiproofimage); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); } catch { } } else { try { iTextSharp.text.Rectangle pageSize = null; WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(resiproofimage); MemoryStream ms = new MemoryStream(bytes); using (var srcImage = new Bitmap(ms)) { if (srcImage.Width < 580) { pageSize = new iTextSharp.text.Rectangle(0, 0, 580, srcImage.Height + 100); } else { pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height + 100); } } //Will eventually hold the PDF with the image as a byte array Byte[] imageBytes; //Simple image to PDF using (var m = new MemoryStream()) { Document d = new Document(pageSize, 0, 0, 0, 0); PdfWriter w = PdfWriter.GetInstance(d, m); d.Open(); d.Add(iTextSharp.text.Image.GetInstance(resiproofimage)); d.Close(); //Grab the bytes before closing out the stream imageBytes = m.ToArray(); } //Now merge using the same merge code as #1 PdfReader reader1 = new PdfReader(imageBytes); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); ms.Close(); } catch { } } } if (documentproof != "http://localhost/yesbank/MobImages/") { try { PdfReader reader1 = new PdfReader(documentproof); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); } catch (Exception ex) { } } doc.Close(); copy.Close(); //Grab the bytes before closing the stream finalFileBytes = finalFile.ToArray(); System.IO.File.WriteAllBytes(finalPDF, finalFileBytes); byte[] bytesaa = File.ReadAllBytes(finalPDF); iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.RED); using (MemoryStream stream = new MemoryStream()) { PdfReader reader = new PdfReader(bytesaa); using (PdfStamper stamper = new PdfStamper(reader, stream)) { int pages = reader.NumberOfPages; for (int i = 1; i <= pages; i++) { ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase("E-CAF No. : " + Ecafno, blackFont), 568f, 15f, 0); } } bytesaa = stream.ToArray(); } File.WriteAllBytes(finalPDF, bytesaa); } } catch { } }
/** * Get the <code>PdfAppearance</code> of a text or combo field * @throws IOException on error * @throws DocumentException on error * @return A <code>PdfAppearance</code> */ public PdfAppearance GetAppearance() { PdfAppearance app = GetBorderAppearance(); app.BeginVariableText(); if (text == null || text.Length == 0) { app.EndVariableText(); return(app); } bool borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET; float h = box.Height - borderWidth * 2 - extraMarginTop; float bw2 = borderWidth; if (borderExtra) { h -= borderWidth * 2; bw2 *= 2; } float offsetX = Math.Max(bw2, 1); float offX = Math.Min(bw2, offsetX); app.SaveState(); app.Rectangle(offX, offX, box.Width - 2 * offX, box.Height - 2 * offX); app.Clip(); app.NewPath(); String ptext; if ((options & PASSWORD) != 0) { ptext = ObfuscatePassword(text); } else if ((options & MULTILINE) == 0) { ptext = RemoveCRLF(text); } else { ptext = text; //fixed by Kazuya Ujihara (ujihara.jp) } BaseFont ufont = RealFont; Color fcolor = (textColor == null) ? GrayColor.GRAYBLACK : textColor; int rtl = CheckRTL(ptext) ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_NO_BIDI; float usize = fontSize; Phrase phrase = ComposePhrase(ptext, ufont, fcolor, usize); if ((options & MULTILINE) != 0) { float width = box.Width - 4 * offsetX - extraMarginLeft; float factor = ufont.GetFontDescriptor(BaseFont.BBOXURY, 1) - ufont.GetFontDescriptor(BaseFont.BBOXLLY, 1); ColumnText ct = new ColumnText(null); if (usize == 0) { usize = h / factor; if (usize > 4) { if (usize > 12) { usize = 12; } float step = Math.Max((usize - 4) / 10, 0.2f); ct.SetSimpleColumn(0, -h, width, 0); ct.Alignment = alignment; ct.RunDirection = rtl; for (; usize > 4; usize -= step) { ct.YLine = 0; ChangeFontSize(phrase, usize); ct.SetText(phrase); ct.Leading = factor * usize; int status = ct.Go(true); if ((status & ColumnText.NO_MORE_COLUMN) == 0) { break; } } } if (usize < 4) { usize = 4; } } ChangeFontSize(phrase, usize); ct.Canvas = app; float leading = usize * factor; float offsetY = offsetX + h - ufont.GetFontDescriptor(BaseFont.BBOXURY, usize); ct.SetSimpleColumn(extraMarginLeft + 2 * offsetX, -20000, box.Width - 2 * offsetX, offsetY + leading); ct.Leading = leading; ct.Alignment = alignment; ct.RunDirection = rtl; ct.SetText(phrase); ct.Go(); } else { if (usize == 0) { float maxCalculatedSize = h / (ufont.GetFontDescriptor(BaseFont.BBOXURX, 1) - ufont.GetFontDescriptor(BaseFont.BBOXLLY, 1)); ChangeFontSize(phrase, 1); float wd = ColumnText.GetWidth(phrase, rtl, 0); if (wd == 0) { usize = maxCalculatedSize; } else { usize = Math.Min(maxCalculatedSize, (box.Width - extraMarginLeft - 4 * offsetX) / wd); } if (usize < 4) { usize = 4; } } ChangeFontSize(phrase, usize); float offsetY = offX + ((box.Height - 2 * offX) - ufont.GetFontDescriptor(BaseFont.ASCENT, usize)) / 2; if (offsetY < offX) { offsetY = offX; } if (offsetY - offX < -ufont.GetFontDescriptor(BaseFont.DESCENT, usize)) { float ny = -ufont.GetFontDescriptor(BaseFont.DESCENT, usize) + offX; float dy = box.Height - offX - ufont.GetFontDescriptor(BaseFont.ASCENT, usize); offsetY = Math.Min(ny, Math.Max(offsetY, dy)); } if ((options & COMB) != 0 && maxCharacterLength > 0) { int textLen = Math.Min(maxCharacterLength, ptext.Length); int position = 0; if (alignment == Element.ALIGN_RIGHT) { position = maxCharacterLength - textLen; } else if (alignment == Element.ALIGN_CENTER) { position = (maxCharacterLength - textLen) / 2; } float step = (box.Width - extraMarginLeft) / maxCharacterLength; float start = step / 2 + position * step; if (textColor == null) { app.SetGrayFill(0); } else { app.SetColorFill(textColor); } app.BeginText(); foreach (Chunk ck in phrase) { BaseFont bf = ck.Font.BaseFont; app.SetFontAndSize(bf, usize); StringBuilder sb = ck.Append(""); for (int j = 0; j < sb.Length; ++j) { String c = sb.ToString(j, 1); float wd = bf.GetWidthPoint(c, usize); app.SetTextMatrix(extraMarginLeft + start - wd / 2, offsetY - extraMarginTop); app.ShowText(c); start += step; } } app.EndText(); } else { float x; switch (alignment) { case Element.ALIGN_RIGHT: x = extraMarginLeft + box.Width - (2 * offsetX); break; case Element.ALIGN_CENTER: x = extraMarginLeft + (box.Width / 2); break; default: x = extraMarginLeft + (2 * offsetX); break; } ColumnText.ShowTextAligned(app, alignment, phrase, x, offsetY - extraMarginTop, 0, rtl, 0); } } app.RestoreState(); app.EndVariableText(); return(app); }
protected internal override void AddText(float x, float y, float height, float width, string[] sa, StyleInfo si, float[] tw, bool bWrap, string url, bool bNoClip, string tooltip) { BaseFont bf; string face = iFontNameNormalize(si.FontFamily); string fontname = ""; bool fonttype1 = true; var folder = FontFolder; //Call to determine folder and set value of _dejavuFonts; if (face == "Times-Roman") { if (si.IsFontBold() && si.FontStyle == FontStyleEnum.Italic) { //OSX if (IsOSX) { face = "TimesNewRomanPS-BoldItalicMT"; fontname = "Times New Roman Bold Italic.ttf"; } else { face = _dejavuFonts ? "DejaVu Serif Condensed Bold Italic" : "Times-BoldItalic"; fontname = (_dejavuFonts ? "DejaVuSerifCondensed-BoldItalic.ttf" : "timesbi.ttf"); } } else if (si.IsFontBold()) { //OSX if (IsOSX) { face = "TimesNewRomanPS-BoldMT"; fontname = "Times New Roman Bold.ttf"; } else { face = _dejavuFonts ? "DejaVu Serif Condensed Bold" : "Times-Bold"; fontname = (_dejavuFonts ? "DejaVuSerifCondensed-Bold.ttf" : "timesbd.ttf"); } } else if (si.FontStyle == FontStyleEnum.Italic) { //OSX if (IsOSX) { face = "TimesNewRomanPS-ItalicMT"; fontname = "Times New Roman Italic.ttf"; } else { face = _dejavuFonts ? "DejaVu Serif Condensed Italic" : "Times-Italic"; fontname = (_dejavuFonts ? "DejaVuSerifCondensed-Italic.ttf" : "timesi.ttf"); } } else { //OSX if (IsOSX) { face = "TimesNewRomanPSMT"; fontname = "Times New Roman.ttf"; } else { face = _dejavuFonts ? "DejaVu Serif Condensed" : face; fontname = (_dejavuFonts ? "DejaVuSerifCondensed.ttf" : "times.ttf"); } } fonttype1 = false; } else if (face == "Arial") { if (si.IsFontBold() && si.FontStyle == FontStyleEnum.Italic) { //OSX if (IsOSX) { face = "Arial BoldItalicMT"; fontname = "Arial Bold Italic.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Condensed Bold Oblique" : "Arial-BoldItalic"; fontname = (_dejavuFonts ? "DejaVuSansCondensed-BoldOblique.ttf" : "arialbi.ttf"); } } else if (si.IsFontBold()) { //OSX if (IsOSX) { face = "Arial-BoldMT"; fontname = "Arial Bold.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Condensed Bold" : "Arial-Bold"; fontname = (_dejavuFonts ? "DejaVuSansCondensed-Bold.ttf" : "arialbd.ttf"); } } else if (si.FontStyle == FontStyleEnum.Italic) { //OSX if (IsOSX) { face = "Arial-ItalicMT"; fontname = "Arial Italic.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Condensed Oblique" : "Arial-Italic"; fontname = (_dejavuFonts ? "DejaVuSansCondensed-Oblique.ttf" : "ariali.ttf"); } } else { //OSX if (IsOSX) { face = "ArialMT"; fontname = "Arial.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Condensed" : face; fontname = (_dejavuFonts ? "DejaVuSansCondensed.ttf" : "arial.ttf"); } } fonttype1 = false; } else if (face == "Courier New") { if (si.IsFontBold() && si.FontStyle == FontStyleEnum.Italic) { //OSX if (IsOSX) { face = "CourierNewPS-BoldItalicMT"; fontname = "Courier New Bold Italic.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Mono Bold Oblique" : "Courier New-BoldItalic"; fontname = (_dejavuFonts ? "DejaVuSansMono-BoldOblique.ttf" : "courbi.ttf"); } } else if (si.IsFontBold()) { //OSX if (IsOSX) { face = "CourierNewPS-BoldMT"; fontname = "Courier New Bold.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Mono Bold" : "Courier New-Bold"; fontname = (_dejavuFonts ? "DejaVuSansMono-Oblique.ttf" : "courbd.ttf"); } } else if (si.FontStyle == FontStyleEnum.Italic) { //OSX if (IsOSX) { face = "CourierNewPS-ItalicMT"; fontname = "Courier New Italic.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Mono Oblique" : "Courier New-Italic"; fontname = (_dejavuFonts ? "DejaVuSansMono-Oblique.ttf" : "couri.ttf"); } } else { //OSX if (IsOSX) { face = "CourierNewPSMT"; fontname = "Courier New.ttf"; } else { face = _dejavuFonts ? "DejaVu Sans Mono" : face; fontname = (_dejavuFonts ? "DejaVuSansMono.ttf" : "cour.ttf"); } } fonttype1 = false; } else { if (si.IsFontBold() && si.FontStyle == FontStyleEnum.Italic) // bold and italic? { face = face + "-BoldOblique"; } else if (si.IsFontBold()) // just bold? { face = face + "-Bold"; } else if (si.FontStyle == FontStyleEnum.Italic) { face = face + "-Oblique"; } fonttype1 = true; } //Get index of fontname in List font name int indexbf = _baseFontsName.FindIndex(delegate(string _fontname) { return(_fontname == face); }); //If not found then add new BaseFont if (indexbf == -1) { _baseFontsName.Add(face); if (fonttype1) { bf = BaseFont.CreateFont(face, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); } else { string path = System.IO.Path.Combine(folder, fontname); bf = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } _baseFonts.Add(bf); } else //Get from List { bf = _baseFonts[indexbf]; } // Loop thru the lines of text for (int i = 0; i < sa.Length; i++) { string text = sa[i]; float textwidth = tw[i]; // Calculate the x positino float startX = x + si.PaddingLeft; // TODO: handle tb_rl float startY = y + si.PaddingTop + (i * si.FontSize); // TODO: handle tb_rl int align = 0; if (si.WritingMode == WritingModeEnum.lr_tb) { // TODO: not sure what alignment means with tb_lr so I'll leave it out for now switch (si.TextAlign) { case TextAlignEnum.Center: if (width > 0) { startX = x + si.PaddingLeft + (width - si.PaddingLeft - si.PaddingRight) / 2 - textwidth / 2; align = Element.ALIGN_CENTER; } break; case TextAlignEnum.Right: if (width > 0) { startX = x + width - textwidth - si.PaddingRight; align = Element.ALIGN_RIGHT; } break; case TextAlignEnum.Left: default: align = Element.ALIGN_LEFT; break; } // Calculate the y position switch (si.VerticalAlign) { case VerticalAlignEnum.Middle: if (height <= 0) { break; } // calculate the middle of the region startY = y + si.PaddingTop + (height - si.PaddingTop - si.PaddingBottom) / 2 - si.FontSize / 2; // now go up or down depending on which line if (sa.Length == 1) { break; } if (sa.Length % 2 == 0) // even number { startY = startY - ((sa.Length / 2 - i) * si.FontSize) + si.FontSize / 2; } else { startY = startY - ((sa.Length / 2 - i) * si.FontSize); } break; case VerticalAlignEnum.Bottom: if (height <= 0) { break; } startY = y + height - si.PaddingBottom - (si.FontSize * (sa.Length - i)); break; case VerticalAlignEnum.Top: default: break; } } else { //25072008 GJL - Move x in a little - it draws to close to the edge of the rectangle (25% of the font size seems to work!) and Center or right align vertical text startX += si.FontSize / 4; switch (si.TextAlign) { case TextAlignEnum.Center: if (height > 0) { startY = y + si.PaddingLeft + (height - si.PaddingLeft - si.PaddingRight) / 2 - textwidth / 2; } break; case TextAlignEnum.Right: if (width > 0) { startY = y + height - textwidth - si.PaddingRight; } break; case TextAlignEnum.Left: default: break; } } // Draw background rectangle if needed (only put out on the first line, since we do whole rectangle) if (!si.BackgroundColor.IsEmpty && height > 0 && width > 0 && i == 0) { // background color, height and width are specified iAddFillRect(x, y, width, height, si.BackgroundColor); } // Set the clipping path, (Itext have no clip) if (height > 0 && width > 0) { _contentByte.SetRGBColorFill(si.Color.R, si.Color.G, si.Color.B); if (si.WritingMode == WritingModeEnum.lr_tb) { //If textline after measure with word break can fit just simple show Text if (width >= textwidth) { _contentByte.BeginText(); _contentByte.SetFontAndSize(bf, si.FontSize); _contentByte.SetTextMatrix(startX, (PageSize.yHeight - startY - si.FontSize)); _contentByte.ShowText(text); _contentByte.EndText(); } else { //else use Column text to wrap or clip (wrap: for example a text like an URL so word break is not working here, itextsharp ColumnText do the work for us) ColumnText ct = new ColumnText(_contentByte); Phrase myPhrase = new Phrase(text, new iTextSharp.text.Font(bf, si.FontSize)); ct.SetSimpleColumn(myPhrase, x + si.PaddingLeft, PageSize.yHeight - startY, x + width - si.PaddingRight, PageSize.yHeight - y - si.PaddingBottom - height, 10f, align); ct.Go(); } } else { //Not checked double rads = -283.0 / 180.0; double radsCos = Math.Cos(rads); double radsSin = Math.Sin(rads); _contentByte.BeginText(); _contentByte.SetFontAndSize(bf, si.FontSize); _contentByte.SetTextMatrix((float)radsCos, (float)radsSin, (float)-radsSin, (float)radsCos, startX, PageSize.yHeight - startY); _contentByte.ShowText(text); _contentByte.EndText(); } //add URL if (url != null) { _pdfDocument.Add(new Annotation(x, PageSize.yHeight - (y + height), width + x, PageSize.yHeight - y, url)); } //add tooltip if (tooltip != null) { _pdfDocument.Add(new Annotation(x, PageSize.yHeight - (y + height), width + x, PageSize.yHeight - y, tooltip)); } } // Handle underlining etc. float maxX; switch (si.TextDecoration) { case TextDecorationEnum.Underline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; AddLine(startX, startY + si.FontSize + 1, maxX, startY + si.FontSize + 1, 1, si.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.LineThrough: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; AddLine(startX, startY + (si.FontSize / 2) + 1, maxX, startY + (si.FontSize / 2) + 1, 1, si.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.Overline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; AddLine(startX, startY + 1, maxX, startY + 1, 1, si.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.None: default: break; } } iAddBorder(si, x, y, height, width); // add any required border return; }
private void DrawOverlayText(PdfContentByte canvas, IList <Rectangle> textRectangles, PdfString overlayText, PdfString otDA, PdfNumber otQ, PdfBoolean otRepeat) { ColumnText ct = new ColumnText(canvas); ct.SetLeading(0, 1.2F); ct.UseAscender = true; String otStr = overlayText.ToUnicodeString(); canvas.SaveState(); IDictionary <string, IList <object> > parsedDA = ParseDAParam(otDA); Font font = null; if (parsedDA.ContainsKey(STROKE_COLOR)) { IList <object> strokeColorArgs = parsedDA[STROKE_COLOR]; SetStrokeColor(canvas, strokeColorArgs); } if (parsedDA.ContainsKey(FILL_COLOR)) { IList <object> fillColorArgs = parsedDA[FILL_COLOR]; SetFillColor(canvas, fillColorArgs); } if (parsedDA.ContainsKey("Tf")) { IList <object> tfArgs = parsedDA["Tf"]; font = RetrieveFontFromAcroForm((PdfName)tfArgs[0], (PdfNumber)tfArgs[1]); } foreach (Rectangle textRect in textRectangles) { ct.SetSimpleColumn(textRect); if (otQ != null) { ct.Alignment = otQ.IntValue; } Phrase otPhrase; if (font != null) { otPhrase = new Phrase(otStr, font); } else { otPhrase = new Phrase(otStr); } float y = ct.YLine; if (otRepeat != null && otRepeat.BooleanValue) { int status = ct.Go(true); while (!ColumnText.HasMoreText(status)) { otPhrase.Add(otStr); ct.SetText(otPhrase); ct.YLine = y; status = ct.Go(true); } } ct.SetText(otPhrase); ct.YLine = y; ct.Go(); } canvas.RestoreState(); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); var rect = new Rectangle(0, 842, 595, 737) { BackgroundColor = new BaseColor(240, 240, 240) }; _cb.Rectangle(rect); //float x = 0; //float y = 737; //_cb.SetRGBColorFill(vertCarmignac.R, vertCarmignac.G, vertCarmignac.B); //_cb.SetRGBColorStroke(vertCarmignac.R, vertCarmignac.G, vertCarmignac.B); //_cb.MoveTo(x, y + 13); //_cb.LineTo(x + 300, y); //_cb.LineTo(x, y - 13); //_cb.ClosePathFillStroke(); ColumnText ct = new ColumnText(_cb); if (writer.PageNumber % 2 == 1) { ct.SetSimpleColumn(400, 740, 590, 830); } else { ct.SetSimpleColumn(42, 740, 232, 830); } if (_isBTO) { ct.AddElement(new Phrase(15, " ", GetVerdana(16F, F.NORMAL /*, BaseColor.WHITE*/))); ct.AddElement(new Phrase(20, "Bulletin de transmission d’ordre", GetVerdana(16F, F.NORMAL /*, BaseColor.WHITE*/))); } else { ct.AddElement(new Phrase(_proposition.Gestion == TypeGestion.GL ? 25 : 18, _proposition.Gestion == TypeGestion.GL ? "Arbitrage à exécuter" : (this._isProposalRefused) ? "Proposition refusée" : "Arbitrage à exécuter et rapport d'adéquation", GetVerdana(14F, F.NORMAL /*, BaseColor.WHITE*/))); ct.AddElement(new Phrase(13, "Numéro : " + _proposition.NumeroProposition, GetVerdana(9F, F.NORMAL /*, BaseColor.WHITE*/))); ct.AddElement(new Phrase(13, "Date : " + _proposition.DateProposition.ToString("dd/MM/yyyy HH:mm"), GetVerdana(9F, F.NORMAL /*, BaseColor.WHITE*/))); if (this._proposition.Gestion != TypeGestion.GL) { ct.AddElement(new Phrase(13, "Validité : 72h (" + _proposition.DateProposition.AddHours(72).ToString("dd/MM/yyyy HH:mm") + ")", GetVerdana(9F, F.NORMAL /*, BaseColor.WHITE*/))); } } ct.Go(); if (!string.IsNullOrEmpty(_topLogoPath) && File.Exists(_topLogoPath)) { var topLogo = System.Drawing.Image.FromFile(_topLogoPath); var logo = Image.GetInstance(topLogo, System.Drawing.Imaging.ImageFormat.Png); if (writer.PageNumber % 2 == 1) { logo.SetAbsolutePosition(42, 750); } else { logo.SetAbsolutePosition(360, 750); } logo.ScaleAbsoluteWidth((int)(657 * 0.16)); logo.ScaleAbsoluteHeight((int)(479 * 0.16)); _cb.AddImage(logo); _cb.Stroke(); } if (!string.IsNullOrEmpty(_footerLogoPath) && File.Exists(_footerLogoPath)) { var footerLogo = System.Drawing.Image.FromFile(_footerLogoPath); var logo = Image.GetInstance(footerLogo, System.Drawing.Imaging.ImageFormat.Png); logo.SetAbsolutePosition(50, 25); logo.ScaleAbsoluteHeight((int)(151 * 0.12)); logo.ScaleAbsoluteWidth((int)(683 * 0.12)); _cb.AddImage(logo); _cb.Stroke(); } ColumnText disclaimer = new ColumnText(_cb); disclaimer.SetSimpleColumn(170, 10, 490, 45); //if (_proposition.Gestion == TypeGestion.GC) disclaimer.AddElement(new Phrase(8, "Entreprise d’Investissement agréée par la Banque de France sous le numéro 19073G Société Anonyme au capital de 289.400€", GetVerdana(5F, F.NORMAL))); disclaimer.AddElement(new Phrase(8, "RCS Paris 512 179 680 ", GetVerdana(5F, F.NORMAL))); disclaimer.AddElement(new Phrase(8, "89 Bd Malesherbes – 75008 Paris", GetVerdana(5F, F.NORMAL))); //else // disclaimer.AddElement(new Phrase(8, "Carmignac Gestion - 24 place Vendôme - 75001 Paris, France - Téléphone : +33 (0)1 73 00 10 50 - Email : [email protected] - Société de gestion de portefeuille(agrément n° GP 97 - 08 du 13 / 03 / 1997) - S.A.au capital de 15 000 000 € -RCS Paris B 349 501 676 - TVA intracommunautaire: FR 303 495 01 676", GetVerdana(5F, F.NORMAL))); disclaimer.Go(); _cb.Stroke(); //Add paging to footer { var text = writer.PageNumber + "/"; _cb.BeginText(); _cb.SetFontAndSize(_bf, 9F); _cb.SetTextMatrix(document.PageSize.GetRight(80), document.PageSize.GetBottom(30)); _cb.ShowText(text); _cb.EndText(); float len = _bf.GetWidthPoint(text, 9F); _cb.AddTemplate(_footerTemplate, document.PageSize.GetRight(80) + len, document.PageSize.GetBottom(30)); } //Move the pointer and draw line to separate footer section from rest of page _cb.MoveTo(40, document.PageSize.GetBottom(50)); _cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); _cb.Stroke(); }
private void CreateReport(string filePath) { AppFileTemplate f = (AppFileTemplate)DataContext; // margins float left = 30; float right = 10; float top = 10; float bottom = 10; float headH = 20; float indent = 5; //string fontName = "C:\\WINDOWS\\FONTS\\CALIBRI.TTF"; string fontName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "CALIBRI.TTF"); iText.Font NormalSatirFont = iText.FontFactory.GetFont(fontName, "CP1254", 10, iText.Font.NORMAL); iText.Font BoldSatirFont = iText.FontFactory.GetFont(fontName, "CP1254", 10, iText.Font.BOLD); iText.Font NormalRiseFont = iText.FontFactory.GetFont(fontName, "CP1254", 8, iText.Font.NORMAL); iText.Font NormalSymbolFont = iText.FontFactory.GetFont(iText.FontFactory.SYMBOL, 10, iText.Font.NORMAL); iText.Document doc = new iText.Document(iText.PageSize.A4, left, right, top, bottom); float xLL = doc.GetLeft(left); float yLL = doc.GetBottom(bottom); float xUR = doc.GetRight(right); float yUR = doc.GetTop(top); float w = xUR - xLL; float h = yUR - yLL; float xUL = xLL; float yUL = yUR; float xLR = xUR; float yLR = yLL; //float graphW = w - 10; //float graphH = graphW * 2 / 3; float graphH = 3 * h / 5; float graphW = w - 10; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); doc.Open(); // direct content PdfContentByte cb = writer.DirectContent; // çizgiler DrawLine(cb, xUR - w, yUR, xUR, yUR); DrawLine(cb, xUR - w, yUR, xLL, yLL); DrawLine(cb, xLL, yLL, xLL + w, yLL); DrawLine(cb, xLL + w, yLL, xUR, yUR); DrawLine(cb, xUL, yUL - headH, xUR, yUR - headH); DrawLine(cb, xUL, yUL - headH - graphH, xUR, yUR - headH - graphH); // başlık ColumnText ct = new ColumnText(cb); ct.Indent = indent; iText.Phrase txt = new iText.Phrase(); txt.Add(new iText.Chunk(f.ReportTitle, NormalSatirFont)); ct.SetSimpleColumn(txt, xUL, yUL - headH, xUR, yUR, headH / 1.5f, iText.Element.ALIGN_LEFT | iText.Element.ALIGN_MIDDLE); ct.Go(); var stream = new MemoryStream(); var pngExporter = new PngExporter { Width = (int)graphW, Height = (int)graphH, Background = OxyColors.White }; pngExporter.Export(PlotView.Model, stream); iText.Image png = iText.Image.GetInstance(stream.GetBuffer()); png.Alignment = iText.Element.ALIGN_CENTER | iText.Element.ALIGN_MIDDLE; png.SetAbsolutePosition(xUL, yUL - headH - graphH); doc.Add(png); float kstW = w / 2; float kstH = (h - headH - graphH) / 1.5f; ColumnText ctKesit = new ColumnText(cb); ctKesit.Indent = indent; txt = new iText.Phrase(); txt.Add(new iText.Chunk("Kesit\n", BoldSatirFont)); txt.Add(new iText.Chunk(String.Format("Genişlik, b = {0:0} cm\n", f.b), NormalSatirFont)); txt.Add(new iText.Chunk(String.Format("Yükseklik, h = {0:0} cm\n", f.h), NormalSatirFont)); txt.Add(new iText.Chunk(String.Format("Alan, bxh = {0:0} cm²\n", f.b * f.h), NormalSatirFont)); txt.Add(new iText.Chunk("\nMalzeme\n", BoldSatirFont)); txt.Add(new iText.Chunk("f", NormalSatirFont)); txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa ", f.Beton().fc.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont)); txt.Add(new iText.Chunk("f", NormalSatirFont)); txt.Add(new iText.Chunk("y", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().fy.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont)); txt.Add(new iText.Chunk("f", NormalSatirFont)); txt.Add(new iText.Chunk("cd", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa ", f.Beton().fcd.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont)); txt.Add(new iText.Chunk("f", NormalSatirFont)); txt.Add(new iText.Chunk("yd", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().fyd.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont)); txt.Add(new iText.Chunk("E", NormalSatirFont)); txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa ", f.Beton().E.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont)); txt.Add(new iText.Chunk("E", NormalSatirFont)); txt.Add(new iText.Chunk("s", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().E.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont)); txt.Add(new iText.Chunk("e", NormalSymbolFont)); txt.Add(new iText.Chunk("cu", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0.0000} m/m ", f.Beton().Ecu), NormalSatirFont)); txt.Add(new iText.Chunk("e", NormalSymbolFont)); txt.Add(new iText.Chunk("yd", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0.00000} m/m\n", f.DonatiCeligi().Eyd), NormalSatirFont)); txt.Add(new iText.Chunk("k", NormalSatirFont)); txt.Add(new iText.Chunk("1", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(String.Format(" = {0:0.000}\n", f.Beton().k1), NormalSatirFont)); ctKesit.SetSimpleColumn(txt, xUL, yUL - headH - graphH - kstH, xUL + kstW, yUL - headH - graphH, 15, iText.Element.ALIGN_LEFT); ctKesit.Go(); ColumnText ctDonati = new ColumnText(cb); txt = new iText.Phrase(); txt.Add(new iText.Chunk("Donatı\n", BoldSatirFont)); int j = 1; foreach (var rb in f.ReinforcingBars) { txt.Add(new iText.Chunk("A", NormalSatirFont)); txt.Add(new iText.Chunk(string.Format("s{0}", j), NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format("={0:0.00} cm², ", rb.As), NormalSatirFont)); txt.Add(new iText.Chunk("d", NormalSatirFont)); txt.Add(new iText.Chunk(string.Format("{0}", j), NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format("={0:0.00} cm\n", rb.di), NormalSatirFont)); j++; } txt.Add(new iText.Chunk("r", NormalSymbolFont)); txt.Add(new iText.Chunk(string.Format("=%{0:0.00}\n", 100.0 * f.ReinforcingBars.Sum(i => i.As) / (f.b * f.h)), NormalSatirFont)); txt.Add(new iText.Chunk("(d", NormalSatirFont)); txt.Add(new iText.Chunk("i", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(":Kesit basınç yüzeyinin donatı eksenine uzaklığı)\n", NormalSatirFont)); txt.Add(new iText.Chunk("\nDayanım Azaltma Katsayıları\n", BoldSatirFont)); txt.Add(new iText.Chunk("f", NormalSymbolFont)); txt.Add(new iText.Chunk("a", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format(" = {0:0.00}, ", f.PhiA), NormalSatirFont)); txt.Add(new iText.Chunk("f", NormalSymbolFont)); txt.Add(new iText.Chunk("b", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format(" = {0:0.00}, ", f.PhiB), NormalSatirFont)); txt.Add(new iText.Chunk("f", NormalSymbolFont)); txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format(" = {0:0.00}", f.PhiC), NormalSatirFont)); //txt.Add(new iText.Chunk("\n\nTasarım:\n", BoldSatirFont)); //txt.Add(new iText.Chunk(f.Code.ToString(), NormalSatirFont)); ctDonati.SetSimpleColumn(txt, xUL + kstW, yUL - headH - graphH - kstH, xUL + 2 * kstW, yUL - headH - graphH, 15, iText.Element.ALIGN_LEFT); ctDonati.Go(); ColumnText ctTesir = new ColumnText(cb); ctTesir.Indent = indent; txt = new iText.Phrase(); txt.Add(new iText.Chunk("Maksimum eksenel basınç, N", NormalSatirFont)); txt.Add(new iText.Chunk("max", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t\n", f.Pmax), NormalSatirFont)); txt.Add(new iText.Chunk("Maksimum eksenel çekme, N", NormalSatirFont)); txt.Add(new iText.Chunk("min", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t\n\n", f.Pmin), NormalSatirFont)); txt.Add(new iText.Chunk("Yönetmelik maksimum eksenel basınç sınırı, N", NormalSatirFont)); txt.Add(new iText.Chunk("max", NormalRiseFont).SetTextRise(-1.0f)); txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t", f.ActualPmax), NormalSatirFont)); ctTesir.SetSimpleColumn(txt, xUL, yUL - headH - graphH - 1.5f * kstH, xUL + kstW, yUL - headH - graphH - kstH, 15, iText.Element.ALIGN_LEFT); ctTesir.Go(); doc.Close(); }
public ActionResult Print() { var students = db.Students.Include(s => s.educationalQualification).Include(s => s.faculty).Include(s => s.year).ToList(); if (Session["searchString"] != null) { SearchViewModel x = (SearchViewModel)Session["searchString"]; if (!String.IsNullOrEmpty(x.searchString1)) { students = students.Where(s => s.firstName.Contains(x.searchString1) || s.secondName.Contains(x.searchString1)).ToList(); } else if (!String.IsNullOrEmpty(x.searchString2)) { students = students.Where(s => s.socialSecurityNumber.Contains(x.searchString2)).ToList(); } else if (!String.IsNullOrEmpty(x.searchString3)) { students = students.Where(s => s.phoneNumber.Contains(x.searchString3)).ToList(); } } //First you create a Document and a PdfWriter and open the Document. Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 15); pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); //Adding double border var content = pdfWriter.DirectContent; var pageBorderRect = new iTextSharp.text.Rectangle(pdfDoc.PageSize); var pageBorderRect2 = new iTextSharp.text.Rectangle(pdfDoc.PageSize); pageBorderRect.Left += pdfDoc.LeftMargin; pageBorderRect.Right -= pdfDoc.RightMargin; pageBorderRect.Top -= pdfDoc.TopMargin; pageBorderRect.Bottom += pdfDoc.BottomMargin; pageBorderRect2.Left += pdfDoc.LeftMargin - 5; pageBorderRect2.Right -= pdfDoc.RightMargin - 5; pageBorderRect2.Top -= pdfDoc.TopMargin - 5; pageBorderRect2.Bottom += pdfDoc.BottomMargin - 5; content.SetColorStroke(BaseColor.BLACK); content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height); content.Rectangle(pageBorderRect2.Left, pageBorderRect2.Bottom, pageBorderRect2.Width, pageBorderRect2.Height); content.Stroke(); //ColumnText.ShowTextAligned(pdfWriter.DirectContent,Element.ALIGN_CENTER, new Phrase("asdasd علي"), 421, 545, 0,PdfWriter.RUN_DIRECTION_RTL,0); BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\Arial.ttf", BaseFont.IDENTITY_H, true); iTextSharp.text.Font fontt = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.UNDERLINE); iTextSharp.text.Font fontt2 = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL); ColumnText column = new ColumnText(pdfWriter.DirectContent); ColumnText column2 = new ColumnText(pdfWriter.DirectContent); column.SetSimpleColumn(0, 520, 470, 570); column.RunDirection = PdfWriter.RUN_DIRECTION_RTL; column.AddElement(new Paragraph("كشف اسماء طلبة جامعة عين شمس", fontt)); column.Go(); column.SetSimpleColumn(0, 520, 810, 570); column.RunDirection = PdfWriter.RUN_DIRECTION_RTL; column.AddElement(new Paragraph("قيادة قوات الدفاع الشعبي و العسكري", fontt)); column.AddElement(new Paragraph("ادارة التربيه العسكريه", fontt)); string dateNow = DateTime.Now.ToString("dd dddd , MMMM, yyyy", new CultureInfo("ar-AE")); column.AddElement(new Paragraph(dateNow, fontt2)); column.Go(); column.SetSimpleColumn(0, 0, 200, 80); column.RunDirection = PdfWriter.RUN_DIRECTION_RTL; column.AddElement(new Paragraph("التوقيع ( ) ", fontt2)); column.AddElement(new Paragraph("مقدم / مصطفي عبدالله", fontt2)); column.AddElement(new Paragraph("مدير ادارة التربية العسكرية", fontt2)); column.Go(); ////Table PdfContentByte pcb = pdfWriter.DirectContent; PdfPTable table = new PdfPTable(5); table.TotalWidth = 782f; iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL); iTextSharp.text.pdf.PdfPCell name = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "الاسم", font)); iTextSharp.text.pdf.PdfPCell ssn = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "الرقم القومي", font)); iTextSharp.text.pdf.PdfPCell phone = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "التليفون", font)); iTextSharp.text.pdf.PdfPCell address = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "العنوان", font)); iTextSharp.text.pdf.PdfPCell faculty = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, "الكلية", font)); name.RunDirection = PdfWriter.RUN_DIRECTION_RTL; ssn.RunDirection = PdfWriter.RUN_DIRECTION_RTL; phone.RunDirection = PdfWriter.RUN_DIRECTION_RTL; address.RunDirection = PdfWriter.RUN_DIRECTION_RTL; faculty.RunDirection = PdfWriter.RUN_DIRECTION_RTL; table.AddCell(phone); table.AddCell(ssn); table.AddCell(faculty); table.AddCell(address); table.AddCell(name); for (int i = 0; i < students.Count; i++) { string cellText5 = students[i].phoneNumber; string cellText4 = students[i].socialSecurityNumber; string cellText6 = students[i].faculty.facultyName; string cellText3 = students[i].address; string cellText2 = students[i].firstName + " " + students[i].secondName + " " + students[i].thirdName + " " + students[i].fourthName; iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText5, font)); iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText4, font)); iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText6, font)); iTextSharp.text.pdf.PdfPCell cell3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText3, font)); iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText2, font)); cell2.RunDirection = PdfWriter.RUN_DIRECTION_RTL; cell3.RunDirection = PdfWriter.RUN_DIRECTION_RTL; cell4.RunDirection = PdfWriter.RUN_DIRECTION_RTL; cell5.RunDirection = PdfWriter.RUN_DIRECTION_RTL; cell6.RunDirection = PdfWriter.RUN_DIRECTION_RTL; table.AddCell(cell5); table.AddCell(cell4); table.AddCell(cell6); table.AddCell(cell3); table.AddCell(cell2); } table.WriteSelectedRows(0, -1, 30, 515, pcb); //pdfDoc.Add(table); //Chunk c1 = new Chunk("A chunk represents an isolated string. "); //font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL); //Chunk c2 = new Chunk("علي صبري",font); //column.SetSimpleColumn(30, 30, 810, 515); //column.AddElement(table); //column.Go(); //To create a Pdf use the below code and place it on the end. pdfWriter.CloseStream = false; pdfDoc.Close(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=StudentEventReport.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Write(pdfDoc); Response.End(); return(View()); }
public void Run(Stream stream, CMSDataContext Db, IEnumerable <ContributorInfo> q, int set = 0) { pageEvents.set = set; pageEvents.PeopleId = 0; IEnumerable <ContributorInfo> contributors = q; var toDate = ToDate.Date.AddHours(24).AddSeconds(-1); PdfContentByte dc; var font = FontFactory.GetFont(FontFactory.HELVETICA, 11); var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11); var doc = new Document(PageSize.LETTER); doc.SetMargins(36f, 30f, 24f, 36f); var w = PdfWriter.GetInstance(doc, stream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; var prevfid = 0; var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.Processed = 0; Db.SubmitChanges(); var count = 0; foreach (var ci in contributors) { if (set > 0 && pageEvents.FamilySet[ci.PeopleId] != set) { continue; } var contributions = APIContribution.contributions(Db, ci, FromDate, toDate).ToList(); var pledges = APIContribution.pledges(Db, ci, toDate).ToList(); var giftsinkind = APIContribution.GiftsInKind(Db, ci, FromDate, toDate).ToList(); var nontaxitems = Db.Setting("DisplayNonTaxOnStatement", "false").ToBool() ? APIContribution.NonTaxItems(Db, ci, FromDate, toDate).ToList() : new List <ContributionInfo>(); if ((contributions.Count + pledges.Count + giftsinkind.Count + nontaxitems.Count) == 0) { runningtotals.Processed += 1; runningtotals.CurrSet = set; Db.SubmitChanges(); if (set == 0) { pageEvents.FamilySet[ci.PeopleId] = 0; } continue; } pageEvents.NextPeopleId = ci.PeopleId; doc.NewPage(); if (prevfid != ci.FamilyId) { prevfid = ci.FamilyId; pageEvents.EndPageSet(); pageEvents.PeopleId = ci.PeopleId; } if (set == 0) { pageEvents.FamilySet[ci.PeopleId] = 0; } count++; var css = @" <style> h1 { font-size: 24px; font-weight:normal; margin-bottom:0; } h2 { font-size: 11px; font-weight:normal; margin-top: 0; } p { font-size: 11px; } </style> "; //----Church Name var t1 = new PdfPTable(1); t1.TotalWidth = 72f * 5f; t1.DefaultCell.Border = Rectangle.NO_BORDER; string html1 = Db.ContentHtml("StatementHeader", Resource1.ContributionStatementHeader); string html2 = Db.ContentHtml("StatementNotice", Resource1.ContributionStatementNotice); var mh = new MyHandler(); using (var sr = new StringReader(css + html1)) XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr); var cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh.elements) { if (e.Chunks.Count > 0) { cell.AddElement(e); } } //cell.FixedHeight = 72f * 1.25f; t1.AddCell(cell); t1.AddCell("\n"); var t1a = new PdfPTable(1); t1a.TotalWidth = 72f * 5f; t1a.DefaultCell.Border = Rectangle.NO_BORDER; var ae = new PdfPTable(1); ae.DefaultCell.Border = Rectangle.NO_BORDER; ae.WidthPercentage = 100; var a = new PdfPTable(1); a.DefaultCell.Indent = 25f; a.DefaultCell.Border = Rectangle.NO_BORDER; a.AddCell(new Phrase(ci.Name, font)); foreach (var line in ci.MailingAddress.SplitLines()) { a.AddCell(new Phrase(line, font)); } cell = new PdfPCell(a) { Border = Rectangle.NO_BORDER }; //cell.FixedHeight = 72f * 1.0625f; ae.AddCell(cell); cell = new PdfPCell(t1a.DefaultCell); cell.AddElement(ae); t1a.AddCell(ae); //-----Notice var t2 = new PdfPTable(1); t2.TotalWidth = 72f * 3f; t2.DefaultCell.Border = Rectangle.NO_BORDER; var envno = ""; if (Db.Setting("PrintEnvelopeNumberOnStatement")) { var ev = Person.GetExtraValue(Db, ci.PeopleId, "EnvelopeNumber"); var s = Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue); if (s.HasValue()) { envno = $" env: {Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue)}"; } } t2.AddCell(Db.Setting("NoPrintDateOnStatement") ? new Phrase($"\nid:{ci.PeopleId}{envno} {ci.CampusId}", font) : new Phrase($"\nprinted: {DateTime.Now:M/d/yy} id:{ci.PeopleId}{envno} {ci.CampusId}", font)); t2.AddCell(""); var mh2 = new MyHandler(); using (var sr = new StringReader(css + html2)) XMLWorkerHelper.GetInstance().ParseXHtml(mh2, sr); cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh2.elements) { if (e.Chunks.Count > 0) { cell.AddElement(e); } } t2.AddCell(cell); // POSITIONING OF ADDRESSES //----Header var yp = doc.BottomMargin + Db.Setting("StatementRetAddrPos", "10.125").ToFloat() * 72f; t1.WriteSelectedRows(0, -1, doc.LeftMargin - 0.1875f * 72f, yp, dc); yp = doc.BottomMargin + Db.Setting("StatementAddrPos", "8.3375").ToFloat() * 72f; t1a.WriteSelectedRows(0, -1, doc.LeftMargin, yp, dc); yp = doc.BottomMargin + 10.125f * 72f; t2.WriteSelectedRows(0, -1, doc.LeftMargin + 72f * 4.4f, yp, dc); //----Contributions doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ") { SpacingBefore = 72f * 2.125f }); doc.Add(new Phrase($"\n Period: {FromDate:d} - {toDate:d}", boldfont)); var pos = w.GetVerticalPosition(true); var ct = new ColumnText(dc); float gutter = 20f; float colwidth = (doc.Right - doc.Left - gutter) / 2; var t = new PdfPTable(new[] { 10f, 24f, 10f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("Contributions\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); t.AddCell(new Phrase("Description", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; var total = 0m; foreach (var c in contributions) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); total += (c.ContributionAmount); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("Total Contributions for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); //------Pledges if (pledges.Count > 0) { t = new PdfPTable(new float[] { 16f, 12f, 12f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nPledges\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Pledge", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Given", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in pledges) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.PledgeAmount.ToString2("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font); t.AddCell(cell); } ct.AddElement(t); } //------Gifts In Kind if (giftsinkind.Count > 0) { t = new PdfPTable(new float[] { 12f, 18f, 20f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nGifts in Kind\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Fund", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Description", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in giftsinkind) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.Fund, font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.Description, font); t.AddCell(cell); } ct.AddElement(t); } //-----Summary t = new PdfPTable(new float[] { 29f, 9f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("\n\nPeriod Summary\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in APIContribution.quarterlySummary(Db, ci, FromDate, toDate)) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); } t.DefaultCell.Border = Rectangle.TOP_BORDER; t.AddCell(new Phrase("Total contributions for period", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); //------NonTax if (nontaxitems.Count > 0) { t = new PdfPTable(new float[] { 10f, 24f, 10f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nNon Tax-Deductible Items\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); t.AddCell(new Phrase("Description", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; var ntotal = 0m; foreach (var c in nontaxitems) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); ntotal += (c.ContributionAmount); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("Total Non Tax-Deductible Items for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(ntotal.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); } var col = 0; var status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos); } else if (col == 1) { ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, pos); } status = ct.Go(); ++col; if (col > 1) { col = 0; pos = doc.Top; doc.NewPage(); } } runningtotals.Processed += 1; runningtotals.CurrSet = set; Db.SubmitChanges(); } if (count == 0) { doc.NewPage(); doc.Add(new Paragraph("no data")); var a = new Anchor("see this help document docs.touchpointsoftware.com/Finance/ContributionStatements.html") { Reference = "http://docs.touchpointsoftware.com/Finance/ContributionStatements.html#troubleshooting" }; doc.Add(a); } doc.Close(); if (set == LastSet()) { runningtotals.Completed = DateTime.Now; } Db.SubmitChanges(); }
public void GeneratePDF(int Id) { var bestellijn = _bestellijnRepository.GetById(Id); var bon = _bonRepository.GetByBonId(bestellijn.Bon.BonId); var handelaar = _handelaarRepository.GetByHandelaarId(bon.Handelaar.HandelaarId); var user = _userManager.GetUserAsync(User); var gebruiker = _gebruikerRepository.GetBy(user.Result.Email); ViewData["path"] = @"/pdf/c_" + bestellijn.QRCode + ".pdf"; string waarde = String.Format("€ " + bestellijn.Prijs.ToString()); string verval = bestellijn.AanmaakDatum.AddYears(1).ToString("dd/MM/yyyy"); string geldigheid = String.Format("Geldig tot: " + verval); var pdf = new Document(PageSize.A5.Rotate(), 81, 225, 25, 0); GenerateQR(bestellijn.QRCode); var imageURL = @"wwwroot/images/temp/" + bestellijn.QRCode + ".png"; iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL); jpg.ScaleToFit(145f, 145f); var logoURL = @"wwwroot/images/logo.png"; var logoURLHandelaar = @"wwwroot" + handelaar.GetLogoPath(); var kadoURL = @"wwwroot/images/kado.jpg"; iTextSharp.text.Image kado = iTextSharp.text.Image.GetInstance(kadoURL); iTextSharp.text.Image logoLL = iTextSharp.text.Image.GetInstance(logoURL); iTextSharp.text.Image logoHandelaar = iTextSharp.text.Image.GetInstance(logoURLHandelaar); logoLL.SetAbsolutePosition(20, 15); logoLL.ScaleToFit(188f, 100f); logoHandelaar.ScaleToFit(188f, 100f); logoHandelaar.SetAbsolutePosition(410, 15); jpg.SetAbsolutePosition(225, 0); kado.SetAbsolutePosition(65, 161); iTextSharp.text.Font arial = FontFactory.GetFont("Arial", 23); iTextSharp.text.Font arial18 = FontFactory.GetFont("Arial", 14); iTextSharp.text.Font arialSmall = FontFactory.GetFont("Arial", 7); Paragraph bedrag = new Paragraph(waarde, arial); bedrag.SpacingAfter = 50; Paragraph naamHandelaar = new Paragraph(bon.Naam, arial); naamHandelaar.SpacingAfter = 0; Paragraph geschonkenDoor = new Paragraph("Geschonken door: " + gebruiker.Voornaam, arial18); Paragraph geldig = new Paragraph(geldigheid, arial18); bedrag.Alignment = Element.ALIGN_LEFT; naamHandelaar.Alignment = Element.ALIGN_LEFT; geschonkenDoor.Alignment = Element.ALIGN_LEFT; geldig.Alignment = Element.ALIGN_LEFT; Phrase qrCodeString = new Phrase(bestellijn.QRCode, arialSmall); PdfWriter writer = PdfWriter.GetInstance(pdf, new FileStream(@"wwwroot/pdf/c_" + bestellijn.QRCode + ".pdf", FileMode.Create)); pdf.Open(); ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_MIDDLE, qrCodeString, 195, 4, 0); pdf.Add(logoLL); pdf.Add(logoHandelaar); pdf.Add(naamHandelaar); pdf.Add(bedrag); pdf.Add(geschonkenDoor); pdf.Add(geldig); pdf.Add(jpg); pdf.Add(kado); pdf.Close(); System.IO.File.Delete(imageURL); }