/* Draw the scores from an array. * content: Drawing content container. * musicArray: Source data. * size: Data size. * count: Number of bars in one line. * tempo: Number of notes in one bar. */ private void DrawFromArray(PdfContentByte content, double[][] musicArray, int size, int count = defaultBarCount, float tempo = defaultTempo) { float beginHeight = defaultBeginHeight; float beginLeft = defaultBeginLeft; float endRight = defaultEndRight; float intervalHeight = defaultIntervalHeight; int line = 0; int c = -1; float width = (endRight - beginLeft) / count; float widthScore = (endRight - beginLeft) / (count * (tempo + 1)); float scoreStart = beginLeft + widthScore; // Music speed. content.BeginText(); content.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED), 10); content.SetTextMatrix(beginLeft, PageSize.A4.Height - beginHeight + 3.5f * lineSpace - intervalHeight); content.ShowText("Moderate = 120"); content.EndText(); DrawOneScore(content, beginLeft + 14 * headSpace, beginHeight - 7 * lineSpace + intervalHeight, 3); // Music tempo. content.BeginText(); content.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 16); content.SetTextMatrix(beginLeft, PageSize.A4.Height - (beginHeight + 2 * lineSpace + intervalHeight)); content.ShowText("4"); content.SetTextMatrix(beginLeft, PageSize.A4.Height - (beginHeight + 4 * lineSpace + intervalHeight)); content.ShowText("4"); content.EndText(); // Draw the scores. double[][] formalMusicArray = MusicFormalization(musicArray, tempo); float curScoreStart = scoreStart; float shortEndRight = 0; double curBarLength = 0; for (int i = 0; i < formalMusicArray.Length; i++) { if (curScoreStart == scoreStart) { line++; Image sign = Image.GetInstance(signPath); sign.SetAbsolutePosition(beginLeft - 18, PageSize.A4.Height - (beginHeight + line * intervalHeight + 5 * lineSpace)); sign.ScaleAbsoluteHeight(6 * lineSpace); sign.ScaleAbsoluteWidth(3.5f * lineSpace); content.AddImage(sign); } DrawOneScore(content, curScoreStart, beginHeight + line * intervalHeight, formalMusicArray[i][0], formalMusicArray[i][1]); curBarLength += formalMusicArray[i][1]; curScoreStart += widthScore; if (i == formalMusicArray.Length - 1) { shortEndRight = curScoreStart; DrawFiveLines(content, beginLeft, shortEndRight + 2, beginHeight + line * intervalHeight); content.MoveTo(curScoreStart, PageSize.A4.Height - (beginHeight + line * intervalHeight)); content.LineTo(curScoreStart, PageSize.A4.Height - (beginHeight + line * intervalHeight) - lineSpace * 4); content.Stroke(); } else { if (curScoreStart >= endRight) { DrawFiveLines(content, beginLeft, endRight, beginHeight + line * intervalHeight); curScoreStart = scoreStart; } if (curBarLength == tempo) { if (curScoreStart + widthScore >= endRight) { DrawFiveLines(content, beginLeft, endRight, beginHeight + line * intervalHeight); curScoreStart = scoreStart; } else if (curScoreStart != scoreStart) { content.MoveTo(curScoreStart, PageSize.A4.Height - (beginHeight + line * intervalHeight)); content.LineTo(curScoreStart, PageSize.A4.Height - (beginHeight + line * intervalHeight) - lineSpace * 4); content.Stroke(); curScoreStart += widthScore; } curBarLength = 0; } } //-------------------------------------------------- /* * if (i % ((int)count * tempo) == 0) * { * line++; * // Draw the sign. * Image sign = Image.GetInstance(signPath); * sign.SetAbsolutePosition(beginLeft - 18, PageSize.A4.Height - (beginHeight + line * intervalHeight + 5 * lineSpace)); * sign.ScaleAbsoluteHeight(6 * lineSpace); * sign.ScaleAbsoluteWidth(3.5f * lineSpace); * content.AddImage(sign); * if (size - i <= count * tempo) * { * int remain = (size - i) / (int)tempo + 1; * if ((size - i) % tempo == 0) * { * remain--; * } * DrawFiveLines(content, beginLeft, beginLeft + ((float)remain / (float)count) * (endRight - beginLeft), beginHeight + line * intervalHeight, remain); * // Dnd vertical line. * content.MoveTo(beginLeft + ((float)remain / (float)count) * (endRight - beginLeft) - headSpace, PageSize.A4.Height - (beginHeight + line * intervalHeight)); * content.LineTo(beginLeft + ((float)remain / (float)count) * (endRight - beginLeft) - headSpace, PageSize.A4.Height - (beginHeight + line * intervalHeight) - lineSpace * 4); * content.Stroke(); * } * else * { * DrawFiveLines(content, beginLeft, endRight, beginHeight + line * intervalHeight, count); * } * } * // Switch to next bar. * if (i % ((int)tempo) == 0) * { * c = (c + 1) % count; * } * DrawOneScore(content, beginLeft + c * width + widthScore * (i % ((int)tempo) + 1), beginHeight + line * intervalHeight, musicArray[i][0], musicArray[i][1]); */ } }
public void OutputText(int x, int y, int flag, int x1, int y1, int x2, int y2, string text) { MetaFont font = state.CurrentFont; float refX = state.TransformX(x); float refY = state.TransformY(y); float angle = state.TransformAngle(font.Angle); float sin = (float)Math.Sin(angle); float cos = (float)Math.Cos(angle); float fontSize = font.GetFontSize(state); BaseFont bf = font.Font; int align = state.TextAlign; float textWidth = bf.GetWidthPoint(text, fontSize); float tx = 0; float ty = 0; float descender = bf.GetFontDescriptor(BaseFont.DESCENT, fontSize); float ury = bf.GetFontDescriptor(BaseFont.BBOXURY, fontSize); cb.SaveState(); cb.ConcatCTM(cos, sin, -sin, cos, refX, refY); if ((align & MetaState.TA_CENTER) == MetaState.TA_CENTER) { tx = -textWidth / 2; } else if ((align & MetaState.TA_RIGHT) == MetaState.TA_RIGHT) { tx = -textWidth; } if ((align & MetaState.TA_BASELINE) == MetaState.TA_BASELINE) { ty = 0; } else if ((align & MetaState.TA_BOTTOM) == MetaState.TA_BOTTOM) { ty = -descender; } else { ty = -ury; } BaseColor textColor; if (state.BackgroundMode == MetaState.OPAQUE) { textColor = state.CurrentBackgroundColor; cb.SetColorFill(textColor); cb.Rectangle(tx, ty + descender, textWidth, ury - descender); cb.Fill(); } textColor = state.CurrentTextColor; cb.SetColorFill(textColor); cb.BeginText(); cb.SetFontAndSize(bf, fontSize); cb.SetTextMatrix(tx, ty); cb.ShowText(text); cb.EndText(); if (font.IsUnderline()) { cb.Rectangle(tx, ty - fontSize / 4, textWidth, fontSize / 15); cb.Fill(); } if (font.IsStrikeout()) { cb.Rectangle(tx, ty + fontSize / 3, textWidth, fontSize / 15); cb.Fill(); } cb.RestoreState(); }
public MemoryStream GeneratePdfTemplate(FPReturnInvToPurchasingViewModel viewModel, int offset) { //Declaring fonts. BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); BaseFont bf_bold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); var normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9); var bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9); //Creating page. Document document = new Document(PageSize.A5.Rotate()); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); PdfContentByte cb = writer.DirectContent; //Set Header #region SetHeader cb.BeginText(); cb.SetTextMatrix(15, 23); cb.SetFontAndSize(bf, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT DAN LIRIS", 20, 385, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Sukoharjo", 20, 370, 0); cb.SetFontAndSize(bf_bold, 14); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "BON RETUR BARANG", 297, 360, 0); cb.SetFontAndSize(bf_bold, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "FM.FP-GB-15-005 / R2", 480, 385, 0); cb.SetFontAndSize(bf, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "KEPADA YTH. BAGIAN PEMBELIAN", 20, 335, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Telah Diretur Ke : " + viewModel.Supplier.name, 20, 320, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "No : " + viewModel.No, 480, 335, 0); cb.EndText(); #endregion #region CreateTable PdfPTable table = new PdfPTable(5); table.TotalWidth = 553f; float[] widths = new float[] { 3f, 10f, 5f, 5f, 10f }; table.SetWidths(widths); var cell = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5 }; var rightCell = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5 }; var leftCell = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5 }; cell.Phrase = new Phrase("No", bold_font); table.AddCell(cell); cell.Phrase = new Phrase("Nama Barang", bold_font); table.AddCell(cell); cell.Phrase = new Phrase("Piece", bold_font); table.AddCell(cell); cell.Phrase = new Phrase("Panjang Total", bold_font); table.AddCell(cell); cell.Phrase = new Phrase("Keterangan", bold_font); table.AddCell(cell); //Add all items. int index = 1; foreach (var item in viewModel.FPReturnInvToPurchasingDetails) { cell.Phrase = new Phrase(index.ToString(), normal_font); table.AddCell(cell); leftCell.Phrase = new Phrase(item.Product.Name, normal_font); table.AddCell(leftCell); rightCell.Phrase = new Phrase(string.Format("{0:n}", item.Quantity), normal_font); table.AddCell(rightCell); rightCell.Phrase = new Phrase(string.Format("{0:n}", item.NecessaryLength), normal_font); table.AddCell(rightCell); leftCell.Phrase = new Phrase(item.Description, normal_font); table.AddCell(leftCell); index++; } //Save tables. table.WriteSelectedRows(0, -1, 20, 310, cb); #endregion cb.SetFontAndSize(bf, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Sukoharjo : " + DateTime.UtcNow.AddHours(offset).ToString("dd-MM-yyyy"), 460, 260, 0); //Set footer #region Footer cb.BeginText(); cb.SetTextMatrix(15, 23); //LEFT cb.SetFontAndSize(bf, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Yang Menyerahkan,", 180, 120, 0); cb.SetFontAndSize(bf, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(..........................)", 180, 50, 0); cb.SetFontAndSize(bf, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Bag. Gudang Material", 180, 35, 0); //RIGHT cb.SetFontAndSize(bf, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Yang Menerima,", 420, 120, 0); cb.SetFontAndSize(bf, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(..........................)", 420, 50, 0); cb.SetFontAndSize(bf, 9); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Bag. Pembelian", 420, 35, 0); cb.EndText(); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
/// <summary> /// Writes text to PDF file on desired position and creates new PDF file. /// </summary> /// <param name="originalPDFpath"> Path to original PDF file. </param> /// <param name="newPDFpath"> Path of PDF to be created. </param> /// <param name="valueToWrite"> Text string to be written. </param> /// <param name="writeOnPage"> Page of PDF. </param> /// <param name="fontFamily"> Font family. </param> /// <param name="fontSize"> Font size. </param> /// <param name="fontColorHex"> Color of font. </param> /// <param name="coordinateX"> X coordinate. </param> /// <param name="coordinateY"> Y coordinate. </param> /// <returns></returns> public static bool WriteText(string originalPDFpath, string newPDFpath, string valueToWrite, int writeOnPage, string fontFamily, decimal fontSize, string fontColorHex, int coordinateX, int coordinateY) { bool res = false; SetPDFPagesCount(originalPDFpath); //string s = Path.GetDirectoryName(originalPDFpath); /* File.Copy(originalPDFpath, newPDFpath); * Color color = System.Drawing.ColorTranslator.FromHtml(fontColorHex); * BaseColor bs = new BaseColor(color); * iTextSharp.text.Font arial = FontFactory.GetFont("Arial", 50, BaseColor.BLUE); * iTextSharp.text.Font font = FontFactory.GetFont(fontFamily,Int32.Parse(fontSize.ToString()), bs); * Phrase phrase = new Phrase(writeValue, arial); * Document doc = new Document(); * iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, * new System.IO.FileStream(newPDFpath, * System.IO.FileMode.Open)); * doc.Open(); * PdfContentByte canvas = writer.DirectContent; * ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, phrase, coordinateX, coordinateY,1);*/ PdfReader reader = new PdfReader(originalPDFpath); iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); // open the writer FileStream fs = new FileStream(newPDFpath, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; PdfContentByte cb2 = writer.DirectContent; Color color = System.Drawing.ColorTranslator.FromHtml(fontColorHex); BaseColor bs = new BaseColor(color); BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false); for (int i = 1; i < pdfPages + 1; i++) { if (i == writeOnPage) { document.NewPage(); PdfImportedPage page = writer.GetImportedPage(reader, writeOnPage); int curRot = reader.GetPageRotation(i); cb.SetColorFill(bs); cb.SetFontAndSize(bfTimes, Int32.Parse(fontSize.ToString())); // write the text in the pdf content cb.BeginText(); // put the alignment and coordinates here cb.ShowTextAligned(1, valueToWrite, coordinateX, coordinateY, 0); cb.EndText(); switch (curRot) { case 0: writer.DirectContent.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); break; case 90: writer.DirectContent.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); break; case 180: writer.DirectContent.AddTemplate(page, -1f, 0, 0, -1f, reader.GetPageSizeWithRotation(i).Width, reader.GetPageSizeWithRotation(i).Height); break; case 270: writer.DirectContent.AddTemplate(page, 0, 1f, -1f, 0, reader.GetPageSizeWithRotation(i).Width, 0); break; } } else { if (i > 1) { document.NewPage(); } PdfImportedPage page2 = writer.GetImportedPage(reader, i); cb2.AddTemplate(page2, 0, 0); } } // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); /* * //creates empty pdf * Document document = new Document(); * * FileStream fs = new FileStream(originalPDFpath, FileMode.OpenOrCreate); * PdfWriter.GetInstance(document, fs); * document.Open(); * document.Add(new Paragraph("Hello World")); * document.Add(new Paragraph(DateTime.Now.ToString())); * * document.Close(); * fs.Close(); */ return(res); }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) { string fullCode; if (codeType == CODE128_RAW) { int idx = code.IndexOf('\uffff'); if (idx < 0) { fullCode = ""; } else { fullCode = code.Substring(idx + 1); } } else if (codeType == CODE128_UCC) { fullCode = GetHumanReadableUCCEAN(code); } else { fullCode = RemoveFNC1(code); } float fontX = 0; if (font != null) { fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } string bCode; if (codeType == CODE128_RAW) { int idx = code.IndexOf('\uffff'); if (idx >= 0) { bCode = code.Substring(0, idx); } else { bCode = code; } } else { bCode = GetRawText(code, codeType == CODE128_UCC); } int len = bCode.Length; float fullWidth = (len + 2) * 11 * x + 2 * x; float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) { barStartX = fontX - fullWidth; } else { textStartX = fullWidth - fontX; } break; default: if (fontX > fullWidth) { barStartX = (fontX - fullWidth) / 2; } else { textStartX = (fullWidth - fontX) / 2; } break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) { textStartY = barHeight - baseline; } else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } byte[] bars = GetBarsCode128Raw(bCode); bool print = true; if (barColor != null) { cb.SetColorFill(barColor); } for (int k = 0; k < bars.Length; ++k) { float w = bars[k] * x; if (print) { cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) { cb.SetColorFill(textColor); } cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return(this.BarcodeSize); }
public override void OnStartPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.DirectContent; cb.BeginText(); float height = writer.PageSize.Height, width = writer.PageSize.Width; float marginLeft = document.LeftMargin, marginTop = document.TopMargin, marginRight = document.RightMargin, marginBottom = document.BottomMargin; int maxSizesCount = viewModel.Items.Max(i => i.Details.Max(d => d.Sizes.GroupBy(g => g.Size.Id).Count())); if (maxSizesCount > 11) { cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED), 6); #region LEFT var logoY = height - marginTop + 65; byte[] imageByteDL = Convert.FromBase64String(Base64ImageStrings.LOGO_DANLIRIS_211_200_BW); Image imageDL = Image.GetInstance(imageByteDL); imageDL.ScaleAbsolute(60f, 60f); var newColor = System.Drawing.Color.Red; imageDL.SetAbsolutePosition(marginLeft, logoY); cb.AddImage(imageDL, inlineImage: true); #endregion #region CENTER var headOfficeX = marginLeft + 75; var headOfficeY = height - marginTop + 105; byte[] imageByte = Convert.FromBase64String(Base64ImageStrings.LOGO_NAME); Image image = Image.GetInstance(imageByte); if (image.Width > 160) { float percentage = 0.0f; percentage = 160 / image.Width; image.ScalePercent(percentage * 100); } image.SetAbsolutePosition(headOfficeX, headOfficeY); cb.AddImage(image, inlineImage: true); string[] headOffices = { "Head Office : Kelurahan Banaran, Kecamatan Grogol,", "Sukoharjo - Indonesia", "PO BOX 166 Solo 57100", "Telp. (62 271) 740888, 714400 (HUNTING)", "Fax. (62 271) 735222, 740777", "Website : www.danliris.com", }; for (int i = 0; i < headOffices.Length; i++) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, headOffices[i], headOfficeX, headOfficeY + 10 - image.ScaledHeight - (i * 6), 0); } #endregion #region RIGHT byte[] imageByteIso = Convert.FromBase64String(Base64ImageStrings.ISO); Image imageIso = Image.GetInstance(imageByteIso); if (imageIso.Width > 80) { float percentage = 0.0f; percentage = 80 / imageIso.Width; imageIso.ScalePercent(percentage * 100); } imageIso.SetAbsolutePosition(width - imageIso.ScaledWidth - marginRight, height - imageIso.ScaledHeight - marginTop + 120); cb.AddImage(imageIso, inlineImage: true); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "CERTIFICATE ID09 / 01238", width - (imageIso.ScaledWidth / 2) - marginRight, height - imageIso.ScaledHeight - marginTop + 120 - 5, 0); #endregion #region LINE cb.MoveTo(marginLeft, height - marginTop + 50); cb.LineTo(width - marginRight, height - marginTop + 50); cb.Stroke(); #endregion cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED), 16); #region TITLE var titleY = height - marginTop + 40; cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "PACKING LIST", width / 2, titleY, 0); #endregion } cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED), 8); #region REF var refY = height - marginTop + 25; cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Ref. No. : FM-00-SP-24-005", width - marginRight, refY, 0); #endregion cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED), 8); #region INFO var infoY = height - marginTop + 10; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Invoice No. : " + viewModel.InvoiceNo, marginLeft, infoY, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Date : " + viewModel.Date.GetValueOrDefault().ToOffset(new TimeSpan(identityProvider.TimezoneOffset, 0, 0)).ToString("MMM dd, yyyy."), width / 2, infoY, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Page : " + writer.PageNumber, width - marginRight, infoY, 0); #endregion #region LINE cb.MoveTo(marginLeft, height - marginTop + 5); cb.LineTo(width - marginRight, height - marginTop + 5); cb.Stroke(); #endregion #region PRINTED var printY = marginBottom - 10; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Waktu Cetak : " + DateTimeOffset.Now.ToOffset(new TimeSpan(identityProvider.TimezoneOffset, 0, 0)).ToString("dd MMMM yyyy H:mm:ss zzz"), marginLeft, printY, 0); #endregion #region SIGNATURE //var signX = width - 140; //var signY = marginBottom - 80; //cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "( MRS. ADRIYANA DAMAYANTI )", signX, signY, 0); //cb.MoveTo(signX - 55, signY - 2); //cb.LineTo(signX + 55, signY - 2); //cb.Stroke(); //cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "AUTHORIZED SIGNATURE", signX, signY - 10, 0); #endregion cb.EndText(); }
public override void OnStartPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.DirectContent; cb.BeginText(); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); float height = writer.PageSize.Height, width = writer.PageSize.Width; float marginLeft = document.LeftMargin - 10, marginTop = document.TopMargin, marginRight = document.RightMargin - 10; cb.SetFontAndSize(bf, 8); #region LEFT var branchOfficeY = height - marginTop + 50; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " HEAD OFFICE :", marginLeft, branchOfficeY, 0); string[] branchOffices = { " Cable : DANLIRIS", " Phone : (62271)740888, 714400", " Website : www.danliris.com", " Fax. : (62271)740777, 735222", }; for (int i = 0; i < branchOffices.Length; i++) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, branchOffices[i], marginLeft, branchOfficeY - 10 - (i * 10), 0); } #endregion #region CENTER var headOfficeX = width / 2 + 30; var headOfficeY = height - marginTop + 60; string[] headOffices = { " Ref. No. : FM-00-SP-24-004", "P.T. DAN LIRIS", "SPINNING - WEAVING - FINISHING - PRINTING - GARMENT", "JL. MERAPI No. 23, KEL. BANARAN, KEC. GROGOL, SUKOHARJO - INDONESIA", "PO. BOX 166 SOLO 57100", " Page " + (writer.PageNumber), // " " }; for (int i = 0; i < headOffices.Length; i++) { cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, headOffices[i], headOfficeX, headOfficeY - (i * 10), 0); } #endregion #region RIGHT BaseColor grey = new BaseColor(128, 128, 128); //cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Page " + (writer.PageNumber), width - (1 / 2) - marginRight, height - marginTop + 20, 0); #endregion cb.EndText(); }
private void CreatePdfText(PdfContentByte content, Configuration.PrintTemplateContentRow row, string text) { CreatePdfBox(content, row); float originX = Convert.ToSingle(row.OriginX) * PointsPerInch; float originY = Convert.ToSingle(row.OriginY) * PointsPerInch; float width = Convert.ToSingle(row.Width) * PointsPerInch; float height = Convert.ToSingle(row.Height) * PointsPerInch; string fontFamily = "Helvetica"; int textAlign = PdfContentByte.ALIGN_CENTER; float fontSize = 12; int textStyle = iTextSharp.text.Font.NORMAL; bool textWrap = false; int columnAlign = Element.ALIGN_CENTER; if (!row.IsTextWrapNull()) { textWrap = row.TextWrap == 1; } if (!row.IsFontFamilyNull()) { fontFamily = row.FontFamily; } if (!row.IsFontBoldNull()) { if (row.FontBold == 1) { if (textWrap) { textStyle = Font.BOLD; } else { fontFamily += "-Bold"; } } } if (!row.IsFontSizeNull()) { fontSize = Convert.ToSingle(row.FontSize); } BaseFont baseFont = BaseFont.CreateFont(fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); if (textWrap) { if (!row.IsTextAlignNull()) { switch (row.TextAlign) { case "left": columnAlign = Element.ALIGN_LEFT; break; case "right": columnAlign = Element.ALIGN_RIGHT; break; } } Font font = new Font(baseFont, fontSize, textStyle); content.SetRGBColorFill(0, 0, 0); float leading = fontSize * 1.2f; ColumnText column = new ColumnText(content); column.SetSimpleColumn(originX, originY, originX + width, originY + height, leading, columnAlign); column.AddText(new Phrase(leading, text, font)); column.Go(); } else { originX += width / 2; if (!row.IsTextAlignNull()) { switch (row.TextAlign) { case "left": textAlign = PdfContentByte.ALIGN_LEFT; originX -= width / 2; break; case "right": textAlign = PdfContentByte.ALIGN_RIGHT; originX += width / 2; break; } } content.BeginText(); content.SetFontAndSize(baseFont, fontSize); content.SetRGBColorFill(0, 0, 0); content.ShowTextAligned(textAlign, text, originX, originY, 0); content.EndText(); } }
private void PrintPickingSlip(PickingSlipReportService service, Document document, PdfWriter writer) { PdfPTable table = new PdfPTable(COLUMNS); table.HeaderRows = 7; PdfPCell cell; string reportTitle = "** LOAN PFI PICKING SLIP **"; if (service.IsPurchase) { reportTitle = "** PURCHASE PFI PICKING SLIP **"; } cell = new PdfPCell(new Phrase(reportTitle, ReportFontBold)); cell.Border = Rectangle.NO_BORDER; cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 10f; cell.PaddingBottom = 10f; cell.Colspan = COLUMNS; table.AddCell(cell); cell = new PdfPCell(new Phrase(ReportContext.RunDate.ToString("d"), ReportFont)); cell.Border = Rectangle.BOTTOM_BORDER; cell.BorderWidth = 2f; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.PaddingTop = 10f; cell.PaddingBottom = 10f; cell.Colspan = 4; table.AddCell(cell); cell = new PdfPCell(new Phrase("Org. #:", ReportFont)); cell.Border = Rectangle.BOTTOM_BORDER; cell.BorderWidth = 2f; cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.PaddingTop = 10f; cell.PaddingBottom = 10f; cell.Colspan = 1; table.AddCell(cell); cell = new PdfPCell(new Phrase(service.OrgNumber.ToString(), ReportFont)); cell.Border = Rectangle.BOTTOM_BORDER; cell.BorderWidth = 2f; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.PaddingTop = 10f; cell.PaddingBottom = 10f; cell.Colspan = 1; table.AddCell(cell); if (service.IsPurchase) { PrintSummaryRow("Customer:", service.Customer, string.Empty, string.Empty, "Purchase Amt:", service.LoanAmount.ToString("c"), table); PrintSummaryRow(string.Empty, string.Empty, "PFI Elig:", service.PfiEligible.ToShortDateString(), string.Empty, string.Empty, table); PrintSummaryRow(string.Empty, string.Empty, "Purchase #:", service.CurrentLoanNumber.ToString(), string.Empty, string.Empty, table); } else { if (service.PartialPayments) { PrintSummaryRow("Customer:", service.Customer, "Loan Amt:", service.LoanAmount.ToString("c"), "Current Principal:", service.CurrentLoanAmount.ToString("c"), table); } else { PrintSummaryRow("Customer:", service.Customer, string.Empty, string.Empty, "Loan Amt:", service.LoanAmount.ToString("c"), table); } PrintSummaryRow("Date Due:", service.DateDue.ToShortDateString(), "PFI Elig:", service.PfiEligible.ToShortDateString(), "Finance:", service.Finance.ToString("c"), table); PrintSummaryRow("Previous Loan #:", service.PreviousLoanNumber.ToString(), "Current Loan #:", service.CurrentLoanNumber.ToString(), "Service:", service.Service.ToString("c"), table); } PrintSummaryRow(string.Empty, string.Empty, string.Empty, string.Empty, "Total:", service.Total.ToString("c"), table); cell = new PdfPCell(new Phrase("Description", ReportFontBold)); cell.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER; cell.BorderWidth = 2f; cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingTop = 10f; cell.PaddingBottom = 10f; cell.Colspan = 4; table.AddCell(cell); cell = new PdfPCell(new Phrase("Location", ReportFontBold)); cell.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER; cell.BorderWidth = 2f; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.PaddingTop = 10f; cell.PaddingBottom = 10f; cell.Colspan = 1; table.AddCell(cell); cell = new PdfPCell(new Phrase("Item Amount", ReportFontBold)); cell.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER; cell.BorderWidth = 2f; cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.PaddingTop = 10f; cell.PaddingBottom = 10f; cell.Colspan = 1; table.AddCell(cell); foreach (PickingSlipReportItem item in service.Items) { cell = new PdfPCell(new Phrase(item.GetItemDescription(), ReportFont)); cell.Border = Rectangle.NO_BORDER; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.Colspan = 4; table.AddCell(cell); cell = new PdfPCell(new Phrase(item.GetLocation(), ReportFont)); cell.Border = Rectangle.NO_BORDER; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.Colspan = 1; table.AddCell(cell); cell = new PdfPCell(new Phrase(item.Amount.ToString("c"), ReportFont)); cell.Border = Rectangle.NO_BORDER; cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Colspan = 1; table.AddCell(cell); } document.Add(table); string text = "EMP#: ___________________ Date#:___________________"; float len = footerBaseFont.GetWidthPoint(text, 8); Rectangle pageSize = document.PageSize; contentByte = writer.DirectContent; template = contentByte.CreateTemplate(50, 50); contentByte.BeginText(); contentByte.SetFontAndSize(footerBaseFont, 8); contentByte.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30)); contentByte.ShowText(text); contentByte.EndText(); contentByte.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30)); document.NewPage(); }
public void Verify_OptionalContentActionExample_CanBeCreated() { var pdfFilePath = TestUtils.GetOutputFileName(); var stream = new FileStream(pdfFilePath, FileMode.Create); // step 1 var document = new Document(); // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PdfVersion = PdfWriter.VERSION_1_5; // step 3 document.AddAuthor(TestUtils.Author); document.Open(); // step 4 PdfLayer a1 = new PdfLayer("answer 1", writer); PdfLayer a2 = new PdfLayer("answer 2", writer); PdfLayer a3 = new PdfLayer("answer 3", writer); a1.On = false; a2.On = false; a3.On = false; BaseFont bf = BaseFont.CreateFont(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); cb.SetFontAndSize(bf, 18); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q1: Who is the director of the movie 'Paths of Glory'?", 50, 766, 0); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q2: Who directed the movie 'Lawrence of Arabia'?", 50, 718, 0); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q3: Who is the director of 'House of Flying Daggers'?", 50, 670, 0); cb.EndText(); cb.SaveState(); cb.SetRgbColorFill(0xFF, 0x00, 0x00); cb.BeginText(); cb.BeginLayer(a1); cb.ShowTextAligned(Element.ALIGN_LEFT, "A1: Stanley Kubrick", 50, 742, 0); cb.EndLayer(); cb.BeginLayer(a2); cb.ShowTextAligned(Element.ALIGN_LEFT, "A2: David Lean", 50, 694, 0); cb.EndLayer(); cb.BeginLayer(a3); cb.ShowTextAligned(Element.ALIGN_LEFT, "A3: Zhang Yimou", 50, 646, 0); cb.EndLayer(); cb.EndText(); cb.RestoreState(); var stateOn = new ArrayList { "ON", a1, a2, a3 }; PdfAction actionOn = PdfAction.SetOcGstate(stateOn, true); var stateOff = new ArrayList { "OFF", a1, a2, a3 }; PdfAction actionOff = PdfAction.SetOcGstate(stateOff, true); var stateToggle = new ArrayList { "Toggle", a1, a2, a3 }; PdfAction actionToggle = PdfAction.SetOcGstate(stateToggle, true); Phrase p = new Phrase("Change the state of the answers:"); Chunk on = new Chunk(" on ").SetAction(actionOn); p.Add(on); Chunk off = new Chunk("/ off ").SetAction(actionOff); p.Add(off); Chunk toggle = new Chunk("/ toggle").SetAction(actionToggle); p.Add(toggle); document.Add(p); document.Close(); stream.Dispose(); TestUtils.VerifyPdfFileIsReadable(pdfFilePath); }
private bool CreateLayerInLegend(PdfContentByte content, Configuration.MapTabRow mapTab, List <CommonLayer> layerList, LegendProperties properties, CommonLayer layer, float indent) { if (!layerList.Contains(layer)) { return(false); } float layerHeight = GetLayerHeightInLegend(layerList, properties, layer); if (properties.CurrentY < properties.Height && properties.CurrentY - layerHeight < 0) { if (properties.CurrentColumn == properties.NumColumns) { return(true); } properties.CurrentX += properties.ColumnWidth + properties.ColumnSpacing; properties.CurrentY = properties.Height; properties.CurrentColumn += 1; } int numClasses = GetNumClasses(layer); Configuration.LayerRow configLayer = mapTab.GetMapTabLayerRows().Where(o => String.Compare(o.LayerRow.LayerName, layer.Name, true) == 0).Select(o => o.LayerRow).FirstOrDefault(); string layerName = configLayer != null && !configLayer.IsDisplayNameNull() ? configLayer.DisplayName : layer.Name; // write the layer name if (layer.Type == CommonLayerType.Group || numClasses > 1) { properties.CurrentY -= properties.FontSize; string name = layerName; try { while (content.GetEffectiveStringWidth(name, false) > properties.ColumnWidth - indent) { name = name.Substring(0, name.Length - 1); } } catch { } content.BeginText(); content.SetFontAndSize(properties.BaseFont, properties.FontSize); content.SetRGBColorFill(0, 0, 0); content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, name, properties.OriginX + properties.CurrentX + indent, properties.OriginY + properties.CurrentY + (properties.SwatchHeight - properties.FontSize) / 2, 0); content.EndText(); } if (layer.Type == CommonLayerType.Group) { properties.CurrentY -= properties.LayerSpacing; foreach (CommonLayer childLayer in layer.Children) { CreateLayerInLegend(content, mapTab, layerList, properties, childLayer, indent + 1.5f * properties.FontSize); } } else { properties.CurrentY -= properties.ClassSpacing; foreach (CommonLegendGroup legendGroup in layer.Legend.Groups) { foreach (CommonLegendClass legendClass in legendGroup.Classes) { if (!legendClass.ImageIsTransparent) { properties.CurrentY -= properties.SwatchHeight; MemoryStream stream = new MemoryStream(legendClass.Image); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream); float w = properties.SwatchHeight * bitmap.Width / bitmap.Height; iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(legendClass.Image); image.SetAbsolutePosition(properties.OriginX + properties.CurrentX + indent, properties.OriginY + properties.CurrentY - properties.SwatchHeight * 0.1f); image.ScaleAbsolute(w, properties.SwatchHeight); content.AddImage(image); string label = numClasses > 1 ? legendClass.Label : layerName; try { while (content.GetEffectiveStringWidth(label, false) > properties.ColumnWidth - properties.SwatchWidth - properties.ClassSpacing) { label = label.Substring(0, label.Length - 1); } } catch { } content.BeginText(); content.SetFontAndSize(properties.BaseFont, properties.FontSize); content.SetRGBColorFill(0, 0, 0); content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, label, properties.OriginX + properties.CurrentX + indent + properties.SwatchWidth + properties.ClassSpacing, properties.OriginY + properties.CurrentY + (properties.SwatchHeight - properties.FontSize) / 2, 0); content.EndText(); properties.CurrentY -= properties.ClassSpacing; } } } properties.CurrentY -= properties.LayerSpacing - properties.ClassSpacing; } return(false); }
public override void OnStartPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.DirectContent; cb.BeginText(); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); float height = writer.PageSize.Height, width = writer.PageSize.Width; float marginLeft = document.LeftMargin - 10, marginTop = document.TopMargin, marginRight = document.RightMargin - 10; cb.SetFontAndSize(bf, 6); #region LEFT var branchOfficeY = height - marginTop + 70; byte[] imageByteDL = Convert.FromBase64String(Base64ImageStrings.LOGO_DANLIRIS_58_58); Image imageDL = Image.GetInstance(imageByteDL); imageDL.SetAbsolutePosition(marginLeft, branchOfficeY); cb.AddImage(imageDL, inlineImage: true); //for (int i = 0; i < branchOffices.Length; i++) //{ // cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, branchOffices[i], marginLeft, branchOfficeY - 10 - (i * 8), 0); //} #endregion #region CENTER var headOfficeX = width / 2 - 200; var headOfficeY = height - marginTop + 110; byte[] imageByte = Convert.FromBase64String(Base64ImageStrings.LOGO_NAME); Image image = Image.GetInstance(imageByte); if (image.Width > 160) { float percentage = 0.0f; percentage = 160 / image.Width; image.ScalePercent(percentage * 100); } image.SetAbsolutePosition(headOfficeX, headOfficeY); cb.AddImage(image, inlineImage: true); string[] headOffices = { "Head Office : JL. MERAPI NO. 23 ", "Banaran, Grogol, Sukoharjo 57193, Central Java, Indonesia", "TELP.: (+62 271) 740888, 714400", "FAX. : (+62 271) 735222, 740777", "PO BOX 166 Solo, 57100", "Website : www.danliris.com", }; for (int i = 0; i < headOffices.Length; i++) { cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, headOffices[i], headOfficeX, headOfficeY - image.ScaledHeight - (i * 10), 0); } #endregion #region RIGHT byte[] imageByteIso = Convert.FromBase64String(Base64ImageStrings.ISO); Image imageIso = Image.GetInstance(imageByteIso); if (imageIso.Width > 100) { float percentage = 0.0f; percentage = 100 / imageIso.Width; imageIso.ScalePercent(percentage * 100); } imageIso.SetAbsolutePosition(width - imageIso.ScaledWidth - marginRight - 30, branchOfficeY); cb.AddImage(imageIso, inlineImage: true); //cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "CERTIFICATE ID09 / 01238", width - (imageIso.ScaledWidth / 2) - marginRight-30, headOfficeY, 0); #endregion #region LINE cb.MoveTo(marginLeft, height - marginTop + 35); cb.LineTo(width - marginRight, height - marginTop + 35); cb.Stroke(); cb.MoveTo(marginLeft, height - marginTop + 32); cb.LineTo(width - marginRight, height - marginTop + 32); cb.Stroke(); #endregion cb.EndText(); }
private void ExportToPDF() { if (DatePickerReport.SelectedDate == null) { MessageBox.Show("Wybierz datę!"); } else { try { DateTime selectedDate = DatePickerReport.SelectedDate.Value.Date; SaveFileDialog dlg = new SaveFileDialog(); string initPath = Path.GetTempPath() + @"\Raport"; dlg.InitialDirectory = Path.GetFullPath(initPath); dlg.RestoreDirectory = true; dlg.FileName = "Raport_" + selectedDate.Date.ToString("dd-MM-yyyy"); dlg.DefaultExt = ".pdf"; dlg.Filter = "Pdf documents (.pdf)|*.pdf"; connection.Open(); Nullable <bool> result = dlg.ShowDialog(); if (result == true) { string filename = dlg.FileName; string query = "SELECT card_index.name AS 'Nazwa produktu', card_index.unit AS 'Jedn.miar', card_index.price AS 'Cena jednostki', ROUND(SUB1.expense_total, 2) AS 'Ilosc', ROUND(SUB1.expense_total * card_index.price, 2) AS 'Wartosc', card_index.file AS 'Nr. kartoteki' FROM(SELECT T1.id_inventory, DATE_FORMAT(T1.date_add_inventory, '%d.%m.%Y') AS date_add_inventory, T1.id_ci_index, T1.id_invoice_index, SUM(T2.expenditure_inventory) AS expense_total FROM inventory T1, inventory T2 WHERE T1.id_inventory = T2.id_inventory AND t1.date_add_inventory = '" + selectedDate.Date.ToString("yyyy-MM-dd") + "' GROUP BY T1.id_ci_index) SUB1 JOIN inventory ON SUB1.id_inventory = inventory.id_inventory INNER JOIN card_index ON inventory.id_ci_index = card_index.id ORDER BY NAME DESC;"; string query2 = "SELECT SUM(Wartosc) AS wartosc1 FROM(SELECT card_index.price AS 'Cena jednostki', ROUND(SUB1.expense_total, 2) AS 'Ilosc', ROUND(SUB1.expense_total * card_index.price, 2) AS Wartosc, card_index.file FROM(SELECT T1.id_inventory, DATE_FORMAT(T1.date_add_inventory, '%d.%m.%Y') AS date_add_inventory, T1.id_ci_index, SUM(T2.expenditure_inventory) AS expense_total FROM inventory T1, inventory T2 WHERE T1.id_inventory = T2.id_inventory AND t1.date_add_inventory = '" + selectedDate.Date.ToString("yyyy-MM-dd") + "' GROUP BY T1.id_ci_index) SUB1 JOIN inventory ON SUB1.id_inventory = inventory.id_inventory INNER JOIN card_index ON inventory.id_ci_index = card_index.id ORDER BY NAME DESC) SUB2;"; MySqlCommand command = new MySqlCommand(query, connection); MySqlDataAdapter adapter = new MySqlDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); MySqlCommand command2 = new MySqlCommand(query2, connection); MySqlDataReader reader = command2.ExecuteReader(); reader.Read(); string totall_price = reader[0].ToString(); reader.Close(); Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); BaseFont f_arial = BaseFont.CreateFont(@"C:\Windows\Fonts\Arial.ttf", BaseFont.CP1250, true); iTextSharp.text.Font fontArial = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); cb.SetFontAndSize(f_arial, 11); PdfPTable table = new PdfPTable(dataTable.Columns.Count) { WidthPercentage = 100 }; for (int k = 0; k < dataTable.Columns.Count; k++) { PdfPCell cell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName, fontArial)) { HorizontalAlignment = PdfPCell.ALIGN_CENTER, VerticalAlignment = PdfPCell.ALIGN_CENTER, BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192) }; table.AddCell(cell); } for (int i = 0; i < dataTable.Rows.Count; i++) { for (int j = 0; j < dataTable.Columns.Count; j++) { PdfPCell cell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString(), fontArial)) { HorizontalAlignment = PdfPCell.ALIGN_CENTER, VerticalAlignment = PdfPCell.ALIGN_CENTER }; table.AddCell(cell); } } Paragraph p = new Paragraph("Kwota wartosci rozchodu: " + totall_price, fontArial) { Alignment = Element.ALIGN_RIGHT }; cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "RAPORT ŻYWIENIOWY", 295, 805, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, selectedDate.Date.ToString("dd.MM.yyyy"), 495, 805, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Podpis dyr. przedszkola:", 100, 70, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Podpis intendenta:", 295, 70, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Podpis kucharki:", 405, 70, 0); cb.SetFontAndSize(f_arial, 5); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Dokument wygenerowany przy pomocy programu gastroEdu", 295, 15, 0); document.Add(new Paragraph("\n")); document.Add(new Paragraph("\n")); document.Add(new Paragraph("\n")); document.Add(table); document.Add(p); cb.EndText(); document.Close(); MessageBox.Show("Utworzono raport."); } } catch (Exception blad) { MessageBox.Show(blad.Message); } } connection.Close(); }
public MemoryStream GeneratePdfTemplate(CostCalculationRetailViewModel viewModel) { BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); BaseFont bf_bold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); DateTime now = DateTime.Now; Document document = new Document(PageSize.A4, 10, 10, 10, 10); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); PdfContentByte cb = writer.DirectContent; float margin = 10; float printedOnHeight = 10; float startY = 840 - margin; PdfPCell cell_colon = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Phrase = new Phrase(":", normal_font) }; #region Header cb.BeginText(); cb.SetFontAndSize(bf, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. EFRATA RETAILINDO", 10, 820, 0); cb.SetFontAndSize(bf_bold, 12); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BUDGET PRODUCTION", 10, 805, 0); cb.EndText(); #endregion #region Detail 1 (Top) PdfPTable table_detail1 = new PdfPTable(8); table_detail1.TotalWidth = 570f; float[] detail1_widths = new float[] { 1f, 0.1f, 2f, 3f, 1f, 0.1f, 2f, 3f }; table_detail1.SetWidths(detail1_widths); PdfPCell cell_detail1 = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; cell_detail1.Phrase = new Phrase("RO", normal_font); table_detail1.AddCell(cell_detail1); table_detail1.AddCell(cell_colon); cell_detail1.Phrase = new Phrase($"{viewModel.RO}", normal_font); table_detail1.AddCell(cell_detail1); cell_detail1.Phrase = new Phrase("", normal_font); table_detail1.AddCell(cell_detail1); cell_detail1.Phrase = new Phrase("SEASON", normal_font); table_detail1.AddCell(cell_detail1); table_detail1.AddCell(cell_colon); cell_detail1.Phrase = new Phrase($"{viewModel.Season.name}", normal_font); table_detail1.AddCell(cell_detail1); cell_detail1.Phrase = new Phrase("", normal_font); table_detail1.AddCell(cell_detail1); #endregion #region Draw Detail 1 float row1Y = 800; table_detail1.WriteSelectedRows(0, -1, 10, row1Y, cb); #endregion #region Detail 2 (Bottom, Column 1) PdfPTable table_detail2 = new PdfPTable(2); table_detail2.TotalWidth = 230f; float[] detail2_widths = new float[] { 2f, 5f }; table_detail2.SetWidths(detail2_widths); PdfPCell cell_detail2 = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7 }; cell_detail2.Phrase = new Phrase("BUYER", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase($"{viewModel.Buyer.Name}", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase("ARTICLE", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase($"{viewModel.Article}", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase("DESCRIPTION", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase($"{viewModel.Description}", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase("QTY", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase($"{viewModel.Quantity} PCS", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase("DELIVERY", normal_font); table_detail2.AddCell(cell_detail2); cell_detail2.Phrase = new Phrase($"{viewModel.DeliveryDate.ToString("dd/MM/yyyy")}", normal_font); table_detail2.AddCell(cell_detail2); #endregion #region Signature PdfPTable table_signature = new PdfPTable(5); table_signature.TotalWidth = 570f; float[] signature_widths = new float[] { 1f, 1f, 1f, 1f, 1f }; table_signature.SetWidths(signature_widths); PdfPCell cell_signature = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; cell_signature.Phrase = new Phrase("Membuat,", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Mengetahui,", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Menyetujui,", normal_font); table_signature.AddCell(cell_signature); string signatureArea = string.Empty; for (int i = 0; i < 4; i++) { signatureArea += Environment.NewLine; } cell_signature.Phrase = new Phrase(signatureArea, normal_font); table_signature.AddCell(cell_signature); table_signature.AddCell(cell_signature); table_signature.AddCell(cell_signature); table_signature.AddCell(cell_signature); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Merchandiser", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Ka. Sie IE", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Ka. Sie Merchandiser", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Ka. Sie Pembelian", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Ka. Div Operasional", normal_font); table_signature.AddCell(cell_signature); #endregion #region Cost Calculation Material PdfPTable table_ccm = new PdfPTable(10); table_ccm.TotalWidth = 570f; float[] ccm_widths = new float[] { 1f, 3f, 4f, 6f, 2f, 3f, 3f, 2f, 3f, 3f }; table_ccm.SetWidths(ccm_widths); PdfPCell cell_ccm = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; cell_ccm.Phrase = new Phrase("NO", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("CATEGORIES", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("MATERIALS", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("DESCRIPTION", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("USAGE", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("PRICE", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("QUANTITY", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("UNIT", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("AMOUNT", bold_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase("PO NUMBER", bold_font); table_ccm.AddCell(cell_ccm); float row2Y = row1Y - table_detail1.TotalHeight - 10; float row3Height = table_detail2.TotalHeight; float row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin; float row2AllowedHeight = row2Y - printedOnHeight - margin; double totalBudget = 0; #region Process Cost double ol = viewModel.OL.CalculatedValue ?? 0; double processCost = ol; #endregion for (int i = 0; i < viewModel.CostCalculationRetail_Materials.Count; i++) { cell_ccm.Phrase = new Phrase((i + 1).ToString(), normal_font); table_ccm.AddCell(cell_ccm); cell_ccm.HorizontalAlignment = Element.ALIGN_LEFT; cell_ccm.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Category.SubCategory != null ? String.Format("{0} - {1}", viewModel.CostCalculationRetail_Materials[i].Category.Name, viewModel.CostCalculationRetail_Materials[i].Category.SubCategory) : viewModel.CostCalculationRetail_Materials[i].Category.Name, normal_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Material.Name, normal_font); table_ccm.AddCell(cell_ccm); cell_ccm.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Description, normal_font); table_ccm.AddCell(cell_ccm); cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT; double usage = viewModel.CostCalculationRetail_Materials[i].Quantity ?? 0; cell_ccm.Phrase = new Phrase(usage.ToString(), normal_font); table_ccm.AddCell(cell_ccm); double price = viewModel.CostCalculationRetail_Materials[i].Price ?? 0; cell_ccm.Phrase = new Phrase(String.Format("{0}/{1}", Number.ToRupiahWithoutSymbol(price), viewModel.CostCalculationRetail_Materials[i].UOMPrice.Name), normal_font); table_ccm.AddCell(cell_ccm); double factor; if (viewModel.CostCalculationRetail_Materials[i].Category.Name == "ACC") { factor = viewModel.AccessoriesAllowance ?? 0; } else { factor = viewModel.FabricAllowance ?? 0; } double totalQuantity = viewModel.Quantity ?? 0; double conversion = (double)viewModel.CostCalculationRetail_Materials[i].Conversion; double usageConversion = usage / conversion; double quantity = (100 + factor) / 100 * usageConversion * totalQuantity; quantity = Math.Ceiling(quantity); cell_ccm.Phrase = new Phrase(quantity.ToString(), normal_font); table_ccm.AddCell(cell_ccm); cell_ccm.HorizontalAlignment = Element.ALIGN_CENTER; cell_ccm.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].UOMPrice.Name, normal_font); table_ccm.AddCell(cell_ccm); cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT; double amount = quantity * price; cell_ccm.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(amount), normal_font); table_ccm.AddCell(cell_ccm); cell_ccm.HorizontalAlignment = Element.ALIGN_CENTER; cell_ccm.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].PO, normal_font); table_ccm.AddCell(cell_ccm); totalBudget += amount; float currentHeight = table_ccm.TotalHeight; if (currentHeight / row2RemainingHeight > 1) { if (currentHeight / row2AllowedHeight > 1) { PdfPRow headerRow = table_ccm.GetRow(0); PdfPRow lastRow = table_ccm.GetRow(table_ccm.Rows.Count - 1); table_ccm.DeleteLastRow(); table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb); table_ccm.DeleteBodyRows(); this.DrawPrintedOn(now, bf, cb); document.NewPage(); table_ccm.Rows.Add(headerRow); table_ccm.Rows.Add(lastRow); table_ccm.CalculateHeights(); row2Y = startY; row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin; row2AllowedHeight = row2Y - printedOnHeight - margin; } } } #endregion #region Detail 3 (Bottom, Column 2) PdfPTable table_detail3 = new PdfPTable(8); table_detail3.TotalWidth = 330f; float[] detail3_widths = new float[] { 3.25f, 4.75f, 1.9f, 0.2f, 1.9f, 1.9f, 0.2f, 1.9f }; table_detail3.SetWidths(detail3_widths); //double budgetCost = viewModel.HPP; double totalProcessCost = processCost * (double)viewModel.Quantity; double budgetCost = totalBudget / (double)viewModel.Quantity; PdfPCell cell_detail3 = new PdfPCell() { HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7 }; PdfPCell cell_detail3_right = new PdfPCell() { HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7 }; PdfPCell cell_detail3_colspan6 = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 6 }; PdfPCell cell_detail3_colspan8 = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 8 }; cell_detail3_colspan8.Phrase = new Phrase("BUDGET COST / PCS" + "".PadRight(5) + $"{Number.ToRupiah(budgetCost)}", normal_font); table_detail3.AddCell(cell_detail3_colspan8); cell_detail3.Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER; cell_detail3.Phrase = new Phrase("TOTAL BUDGET COST", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER; cell_detail3.Phrase = new Phrase("".PadRight(7) + $"{Number.ToRupiah(totalBudget)}", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3_colspan6.Phrase = new Phrase("STANDARD HOURS", normal_font); table_detail3.AddCell(cell_detail3_colspan6); cell_detail3.Border = Rectangle.LEFT_BORDER; cell_detail3.Phrase = new Phrase("", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.RIGHT_BORDER; table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.LEFT_BORDER; cell_detail3.Phrase = new Phrase("SMV. CUT", normal_font); table_detail3.AddCell(cell_detail3); table_detail3.AddCell(cell_colon); cell_detail3.Border = Rectangle.NO_BORDER; double SH_Cutting = viewModel.SH_Cutting ?? 0; cell_detail3.Phrase = new Phrase($"{SH_Cutting}", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.NO_BORDER; cell_detail3.Phrase = new Phrase("SMV. SEW", normal_font); table_detail3.AddCell(cell_detail3); table_detail3.AddCell(cell_colon); cell_detail3.Border = Rectangle.RIGHT_BORDER; double SH_Sewing = viewModel.SH_Sewing ?? 0; cell_detail3.Phrase = new Phrase($"{SH_Sewing}", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER; cell_detail3.Phrase = new Phrase("", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER; cell_detail3.Phrase = new Phrase("", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER; cell_detail3.Phrase = new Phrase("SMV. FIN", normal_font); table_detail3.AddCell(cell_detail3); table_detail3.AddCell(cell_colon); cell_detail3.Border = Rectangle.BOTTOM_BORDER; double SH_Finishing = viewModel.SH_Finishing ?? 0; cell_detail3.Phrase = new Phrase($"{SH_Finishing}", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3.Border = Rectangle.BOTTOM_BORDER; cell_detail3.Phrase = new Phrase("SMV. TOT", normal_font); table_detail3.AddCell(cell_detail3); table_detail3.AddCell(cell_colon); cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER; double SH_Total = SH_Cutting + SH_Sewing + SH_Finishing; cell_detail3.Phrase = new Phrase($"{SH_Total}", normal_font); table_detail3.AddCell(cell_detail3); cell_detail3_colspan8.Phrase = new Phrase("PROCESS COST / PCS" + "".PadRight(5) + $"{Number.ToRupiah(processCost)}", normal_font); table_detail3.AddCell(cell_detail3_colspan8); cell_detail3_colspan8.Phrase = new Phrase("TOTAL PROCESS COST" + "".PadRight(3) + $"{Number.ToRupiah(totalProcessCost)}", normal_font); table_detail3.AddCell(cell_detail3_colspan8); #endregion #region Draw Others table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb); float row3Y = row2Y - table_ccm.TotalHeight - 10; float row3RemainigHeight = row3Y - printedOnHeight - margin; if (row3RemainigHeight < row3Height) { this.DrawPrintedOn(now, bf, cb); row3Y = startY; document.NewPage(); } table_detail2.WriteSelectedRows(0, -1, margin, row3Y, cb); table_detail3.WriteSelectedRows(0, -1, margin + table_detail2.TotalWidth + 10, row3Y, cb); float signatureY = row3Y - row3Height - 10; signatureY = signatureY - 20; float signatureRemainingHeight = signatureY - printedOnHeight - margin; if (signatureRemainingHeight < table_signature.TotalHeight) { this.DrawPrintedOn(now, bf, cb); signatureY = startY; document.NewPage(); } table_signature.WriteSelectedRows(0, -1, margin, signatureY, cb); this.DrawPrintedOn(now, bf, cb); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { String fullCode = code; if (generateChecksum && checksumText) fullCode = CalculateChecksum(code); if (!startStopText) fullCode = fullCode.Substring(1, fullCode.Length - 2); float fontX = 0; if (font != null) { fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } byte[] bars = GetBarsCodabar(generateChecksum ? CalculateChecksum(code) : code); int wide = 0; for (int k = 0; k < bars.Length; ++k) { wide += (int)bars[k]; } int narrow = bars.Length - wide; float fullWidth = x * (narrow + wide * n); float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) barStartX = fontX - fullWidth; else textStartX = fullWidth - fontX; break; default: if (fontX > fullWidth) barStartX = (fontX - fullWidth) / 2; else textStartX = (fullWidth - fontX) / 2; break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) textStartY = barHeight - baseline; else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } bool print = true; if (barColor != null) cb.SetColorFill(barColor); for (int k = 0; k < bars.Length; ++k) { float w = (bars[k] == 0 ? x : x * n); if (print) cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) cb.SetColorFill(textColor); cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return BarcodeSize; }
public MemoryStream GeneratePdfTemplate(RO_RetailViewModel viewModel) { BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); BaseFont bf_bold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); Font bold_font_8 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font font_9 = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9); DateTime now = DateTime.Now; Document document = new Document(PageSize.A4, 10, 10, 10, 10); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); PdfContentByte cb = writer.DirectContent; float margin = 10; float printedOnHeight = 10; float startY = 840 - margin; #region Header cb.BeginText(); cb.SetFontAndSize(bf, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. EFRATA RETAILINDO", 10, 820, 0); cb.SetFontAndSize(bf_bold, 12); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "RO RETAIL", 10, 805, 0); cb.EndText(); #endregion #region Top PdfPTable table_top = new PdfPTable(9); float[] top_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1f, 0.1f, 2f }; table_top.TotalWidth = 500f; table_top.SetWidths(top_widths); PdfPCell cell_top = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; PdfPCell cell_colon = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE }; PdfPCell cell_top_keterangan = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2, Colspan = 7 }; cell_colon.Phrase = new Phrase(":", normal_font); cell_top.Phrase = new Phrase("NO RO", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.CostCalculationRetail.RO}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("ARTICLE", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.CostCalculationRetail.Article}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("STYLE", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.CostCalculationRetail.Style.name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("COUNTER", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.CostCalculationRetail.Counter.name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("COLOUR", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Color.name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("DELIVERY DATE", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.CostCalculationRetail.DeliveryDate.ToString("dd MMMM yyyy")}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("RO QUANTITY", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top_keterangan.Phrase = new Phrase($"{viewModel.Total}", normal_font); table_top.AddCell(cell_top_keterangan); cell_top.Phrase = new Phrase("RO DESCRIPTION", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top_keterangan.Phrase = new Phrase(viewModel.CostCalculationRetail.Description ?? "", normal_font); table_top.AddCell(cell_top_keterangan); #endregion #region Image byte[] imageByte; float imageHeight; try { imageByte = Convert.FromBase64String(Base64.GetBase64File(viewModel.CostCalculationRetail.ImageFile)); Image image = Image.GetInstance(imgb: imageByte); if (image.Width > 60) { float percentage = 0.0f; percentage = 60 / image.Width; image.ScalePercent(percentage * 100); } float imageY = 800 - image.ScaledHeight; imageHeight = image.ScaledHeight; image.SetAbsolutePosition(520, imageY); cb.AddImage(image, inlineImage: true); } catch (Exception) { imageHeight = 0; } #endregion #region Draw Top float row1Y = 800; table_top.WriteSelectedRows(0, -1, 10, row1Y, cb); #endregion #region Fabric Table Title PdfPTable table_fabric_top = new PdfPTable(1); table_fabric_top.TotalWidth = 500f; float[] fabric_widths_top = new float[] { 5f }; table_fabric_top.SetWidths(fabric_widths_top); PdfPCell cell_top_fabric = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; cell_top_fabric.Phrase = new Phrase("FABRIC", bold_font); table_fabric_top.AddCell(cell_top_fabric); float row1Height = imageHeight > table_top.TotalHeight ? imageHeight : table_top.TotalHeight; float rowYTittleFab = row1Y - row1Height - 10; float allowedRow2Height = rowYTittleFab - printedOnHeight - margin; #endregion #region Fabric Table PdfPTable table_fabric = new PdfPTable(5); table_fabric.TotalWidth = 500f; float[] fabric_widths = new float[] { 5f, 5f, 5f, 5f, 5f }; table_fabric.SetWidths(fabric_widths); var fabIndex = 0; PdfPCell cell_fabric_center = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_fabric_left = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; float rowYFab = rowYTittleFab - table_fabric_top.TotalHeight - 5; float allowedRow2HeightFab = rowYFab - printedOnHeight - margin; cell_fabric_center.Phrase = new Phrase("FABRIC", bold_font); table_fabric.AddCell(cell_fabric_center); cell_fabric_center.Phrase = new Phrase("NAME", bold_font); table_fabric.AddCell(cell_fabric_center); cell_fabric_center.Phrase = new Phrase("DESCRIPTION", bold_font); table_fabric.AddCell(cell_fabric_center); cell_fabric_center.Phrase = new Phrase("QUANTITY", bold_font); table_fabric.AddCell(cell_fabric_center); cell_fabric_center.Phrase = new Phrase("REMARK", bold_font); table_fabric.AddCell(cell_fabric_center); foreach (var materialModel in viewModel.CostCalculationRetail.CostCalculationRetail_Materials) { if (materialModel.Category.Name == "FAB") { cell_fabric_left.Phrase = new Phrase(materialModel.Category.SubCategory != null ? materialModel.Category.SubCategory : "", normal_font); table_fabric.AddCell(cell_fabric_left); cell_fabric_left.Phrase = new Phrase(materialModel.Material.Name != null ? materialModel.Material.Name : "", normal_font); table_fabric.AddCell(cell_fabric_left); cell_fabric_left.Phrase = new Phrase(materialModel.Description != null ? materialModel.Description : "", normal_font); table_fabric.AddCell(cell_fabric_left); cell_fabric_left.Phrase = new Phrase(materialModel.Quantity != null ? String.Format("{0} " + materialModel.UOMQuantity.Name, materialModel.Quantity) : "0", normal_font); table_fabric.AddCell(cell_fabric_left); cell_fabric_left.Phrase = new Phrase(materialModel.Information != null ? materialModel.Information : "", normal_font); table_fabric.AddCell(cell_fabric_left); fabIndex++; } } if (fabIndex != 0) { table_fabric_top.WriteSelectedRows(0, -1, 10, rowYTittleFab, cb); table_fabric.WriteSelectedRows(0, -1, 10, rowYFab, cb); } #endregion #region Accessoris Table Title PdfPTable table_acc_top = new PdfPTable(1); table_acc_top.TotalWidth = 500f; float[] acc_width_top = new float[] { 5f }; table_acc_top.SetWidths(acc_width_top); PdfPCell cell_top_acc = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; cell_top_acc.Phrase = new Phrase("ACCESSORIES", bold_font); table_acc_top.AddCell(cell_top_acc); float rowYTittleAcc = rowYFab - table_fabric.TotalHeight - 10; float allowedRow2HeightTopAcc = rowYTittleFab - printedOnHeight - margin; #endregion #region Accessoris Table PdfPTable table_accessories = new PdfPTable(5); table_accessories.TotalWidth = 500f; float[] accessories_widths = new float[] { 5f, 5f, 5f, 5f, 5f }; table_accessories.SetWidths(accessories_widths); var accIndex = 0; PdfPCell cell_acc_center = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_acc_left = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; float rowYAcc = rowYTittleAcc - table_fabric_top.TotalHeight - 5; float allowedRow2HeightAcc = rowYAcc - printedOnHeight - margin; cell_acc_center.Phrase = new Phrase("ACCESSORIES", bold_font); table_accessories.AddCell(cell_acc_center); cell_acc_center.Phrase = new Phrase("NAME", bold_font); table_accessories.AddCell(cell_acc_center); cell_acc_center.Phrase = new Phrase("DESCRIPTION", bold_font); table_accessories.AddCell(cell_acc_center); cell_acc_center.Phrase = new Phrase("QUANTITY", bold_font); table_accessories.AddCell(cell_acc_center); cell_acc_center.Phrase = new Phrase("REMARK", bold_font); table_accessories.AddCell(cell_acc_center); foreach (var materialModel in viewModel.CostCalculationRetail.CostCalculationRetail_Materials) { if (materialModel.Category.Name == "ACC") { cell_acc_left.Phrase = new Phrase(materialModel.Category.SubCategory != null ? materialModel.Category.SubCategory : "", normal_font); table_accessories.AddCell(cell_acc_left); cell_acc_left.Phrase = new Phrase(materialModel.Material.Name != null ? materialModel.Material.Name : "", normal_font); table_accessories.AddCell(cell_acc_left); cell_acc_left.Phrase = new Phrase(materialModel.Description != null ? materialModel.Description : "", normal_font); table_accessories.AddCell(cell_acc_left); cell_acc_left.Phrase = new Phrase(materialModel.Quantity != null ? String.Format("{0} " + materialModel.UOMQuantity.Name, materialModel.Quantity) : "0", normal_font); table_accessories.AddCell(cell_acc_left); cell_acc_left.Phrase = new Phrase(materialModel.Information != null ? materialModel.Information : "", normal_font); table_accessories.AddCell(cell_acc_left); accIndex++; } } if (accIndex != 0) { table_acc_top.WriteSelectedRows(0, -1, 10, rowYTittleAcc, cb); table_accessories.WriteSelectedRows(0, -1, 10, rowYAcc, cb); } #endregion #region Ongkos Table Title PdfPTable table_ong_top = new PdfPTable(1); table_ong_top.TotalWidth = 500f; float[] ong_width_top = new float[] { 5f }; table_ong_top.SetWidths(ong_width_top); PdfPCell cell_top_ong = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; cell_top_ong.Phrase = new Phrase("ONGKOS", bold_font); table_ong_top.AddCell(cell_top_ong); float rowYTittleOng = rowYAcc - table_accessories.TotalHeight - 10; float allowedRow2HeightTopOng = rowYTittleOng - printedOnHeight - margin; #endregion #region Ongkos Table PdfPTable table_budget = new PdfPTable(5); table_budget.TotalWidth = 500f; float[] budget_widths = new float[] { 5f, 5f, 5f, 5f, 5f }; table_budget.SetWidths(budget_widths); var ongIndex = 0; PdfPCell cell_budget_center = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_budget_left = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; float rowYBudget = rowYTittleOng - table_ong_top.TotalHeight - 5; float allowedRow2HeightBudget = rowYBudget - printedOnHeight - margin; cell_budget_center.Phrase = new Phrase("ONGKOS", bold_font); table_budget.AddCell(cell_budget_center); cell_budget_center.Phrase = new Phrase("NAME", bold_font); table_budget.AddCell(cell_budget_center); cell_budget_center.Phrase = new Phrase("DESCRIPTION", bold_font); table_budget.AddCell(cell_budget_center); cell_budget_center.Phrase = new Phrase("QUANTITY", bold_font); table_budget.AddCell(cell_budget_center); cell_budget_center.Phrase = new Phrase("REMARK", bold_font); table_budget.AddCell(cell_budget_center); foreach (var materialModel in viewModel.CostCalculationRetail.CostCalculationRetail_Materials) { if (materialModel.Category.Name == "ONG") { cell_budget_left.Phrase = new Phrase(materialModel.Category.SubCategory != null ? materialModel.Category.SubCategory : "", normal_font); table_budget.AddCell(cell_budget_left); cell_budget_left.Phrase = new Phrase(materialModel.Material.Name != null ? materialModel.Material.Name : "", normal_font); table_budget.AddCell(cell_budget_left); cell_budget_left.Phrase = new Phrase(materialModel.Description != null ? materialModel.Description : "", normal_font); table_budget.AddCell(cell_budget_left); cell_budget_left.Phrase = new Phrase(materialModel.Quantity != null ? String.Format("{0} " + materialModel.UOMQuantity.Name, materialModel.Quantity) : "0", normal_font); table_budget.AddCell(cell_budget_left); cell_budget_left.Phrase = new Phrase(materialModel.Information != null ? materialModel.Information : "", normal_font); table_budget.AddCell(cell_budget_left); ongIndex++; } } if (ongIndex != 0) { table_budget.WriteSelectedRows(0, -1, 10, rowYBudget, cb); table_ong_top.WriteSelectedRows(0, -1, 10, rowYTittleOng, cb); } #endregion #region Size Breakdown Title PdfPTable table_breakdown_top = new PdfPTable(1); table_breakdown_top.TotalWidth = 570f; float[] breakdown_width_top = new float[] { 5f }; table_breakdown_top.SetWidths(breakdown_width_top); PdfPCell cell_top_breakdown = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; cell_top_breakdown.Phrase = new Phrase("SIZE BREAKDOWN", bold_font); table_breakdown_top.AddCell(cell_top_breakdown); float rowYTittleBreakDown = rowYBudget - table_budget.TotalHeight - 10; float allowedRow2HeightBreakdown = rowYTittleBreakDown - printedOnHeight - margin; if (ongIndex == 0) { rowYTittleBreakDown = rowYBudget; } table_breakdown_top.WriteSelectedRows(0, -1, 5, rowYTittleBreakDown, cb); #endregion #region == Table Size Breakdown == var tableBreakdownColumn = 3; PdfPCell cell_breakDown_center = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_breakDown_left = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_breakDown_total = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_breakDown_total_2 = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; float rowYbreakDown = rowYTittleBreakDown - table_breakdown_top.TotalHeight - 5; float allowedRow2HeightBreakDown = rowYbreakDown - printedOnHeight - margin; var remainingRowToHeightBrekdown = rowYbreakDown - 5 - printedOnHeight - margin; List <String> breakdownSizes = new List <string>(); foreach (var size in viewModel.RO_Retail_SizeBreakdowns) { var sizes = size.SizeQuantity.Keys; foreach (var values in sizes) { if (!breakdownSizes.Contains(values)) { breakdownSizes.Add(values); tableBreakdownColumn++; } } } PdfPTable table_breakDown = new PdfPTable(tableBreakdownColumn); table_breakDown.TotalWidth = 570f; List <float> breakdownWidth = new List <float>(); breakdownWidth.Add(1f); breakdownWidth.Add(3f); cell_breakDown_center.Phrase = new Phrase("STORE CODE", bold_font); table_breakDown.AddCell(cell_breakDown_center); cell_breakDown_center.Phrase = new Phrase("STORE", bold_font); table_breakDown.AddCell(cell_breakDown_center); foreach (var size in breakdownSizes) { breakdownWidth.Add(1f); cell_breakDown_center.Phrase = new Phrase(size, bold_font); table_breakDown.AddCell(cell_breakDown_center); } breakdownWidth.Add(1f); cell_breakDown_center.Phrase = new Phrase("TOTAL", bold_font); table_breakDown.AddCell(cell_breakDown_center); float[] breakdown_width = breakdownWidth.ToArray(); table_breakDown.SetWidths(breakdown_width); foreach (var productRetail in viewModel.RO_Retail_SizeBreakdowns) { if (productRetail.Total != 0) { cell_breakDown_left.Phrase = new Phrase(productRetail.Store.code != null ? productRetail.Store.code : "", normal_font); table_breakDown.AddCell(cell_breakDown_left); cell_breakDown_left.Phrase = new Phrase(productRetail.Store.name != null ? productRetail.Store.name : "", normal_font); table_breakDown.AddCell(cell_breakDown_left); foreach (var size in productRetail.SizeQuantity) { foreach (var sizeHeader in breakdownSizes) { if (size.Key == sizeHeader) { cell_breakDown_left.Phrase = new Phrase(size.Value.ToString() != null ? size.Value.ToString() : "0", normal_font); table_breakDown.AddCell(cell_breakDown_left); } } } cell_breakDown_left.Phrase = new Phrase(productRetail.Total.ToString() != null ? productRetail.Total.ToString() : "0", normal_font); table_breakDown.AddCell(cell_breakDown_left); var tableBreakdownCurrentHeight = table_breakDown.TotalHeight; if (tableBreakdownCurrentHeight / remainingRowToHeightBrekdown > 1) { if (tableBreakdownCurrentHeight / allowedRow2HeightBreakDown > 1) { PdfPRow headerRow = table_breakDown.GetRow(0); PdfPRow lastRow = table_breakDown.GetRow(table_breakDown.Rows.Count - 1); table_breakDown.DeleteLastRow(); table_breakDown.WriteSelectedRows(0, -1, 10, rowYbreakDown, cb); table_breakDown.DeleteBodyRows(); this.DrawPrintedOn(now, bf, cb); document.NewPage(); table_breakDown.Rows.Add(headerRow); table_breakDown.Rows.Add(lastRow); table_breakDown.CalculateHeights(); rowYbreakDown = startY; remainingRowToHeightBrekdown = rowYbreakDown - 5 - printedOnHeight - margin; allowedRow2HeightBreakDown = remainingRowToHeightBrekdown - printedOnHeight - margin; } } } } cell_breakDown_total.Phrase = new Phrase(" ", bold_font); table_breakDown.AddCell(cell_breakDown_total); cell_breakDown_total_2.Phrase = new Phrase("TOTAL", bold_font); table_breakDown.AddCell(cell_breakDown_total_2); foreach (var sizeTotal in breakdownSizes) { foreach (var sizeHeader in viewModel.SizeQuantityTotal) { if (sizeHeader.Key == sizeTotal) { cell_breakDown_left.Phrase = new Phrase(sizeHeader.Value.ToString() != null ? sizeHeader.Value.ToString() : "0", normal_font); table_breakDown.AddCell(cell_breakDown_left); } } } cell_breakDown_left.Phrase = new Phrase(viewModel.Total.ToString() != null ? viewModel.Total.ToString() : "0", normal_font); table_breakDown.AddCell(cell_breakDown_left); table_breakDown.WriteSelectedRows(0, -1, 10, rowYbreakDown, cb); #endregion #region Table Instruksi PdfPTable table_instruction = new PdfPTable(1); float[] instruction_widths = new float[] { 400f }; table_instruction.TotalWidth = 500f; table_instruction.SetWidths(instruction_widths); PdfPCell cell_top_instruction = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; PdfPCell cell_colon_instruction = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE }; PdfPCell cell_top_keterangan_instruction = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2, Colspan = 7 }; cell_top_instruction.Phrase = new Phrase("INSTRUCTION", normal_font); table_instruction.AddCell(cell_top_instruction); table_instruction.AddCell(cell_colon_instruction); cell_top_keterangan_instruction.Phrase = new Phrase($"{viewModel.Instruction}", normal_font); table_instruction.AddCell(cell_top_keterangan_instruction); float rowYInstruction = rowYbreakDown - table_breakDown.TotalHeight - 5; float allowedRow2HeightInstruction = rowYInstruction - printedOnHeight - margin; var remainingRowToHeightInstruction = rowYInstruction - 5 - printedOnHeight - margin; var tableInstructionCurrentHeight = table_instruction.TotalHeight; if (remainingRowToHeightInstruction < 0) { remainingRowToHeightInstruction = remainingRowToHeightInstruction * -1; } if (allowedRow2HeightInstruction < 0) { allowedRow2HeightInstruction = allowedRow2HeightInstruction * -1; } if (tableInstructionCurrentHeight / remainingRowToHeightInstruction > 1) { if (tableInstructionCurrentHeight / allowedRow2HeightInstruction > 1) { PdfPRow headerRow = table_instruction.GetRow(0); PdfPRow lastRow = table_instruction.GetRow(table_instruction.Rows.Count - 1); table_instruction.DeleteLastRow(); table_instruction.WriteSelectedRows(0, -1, 10, rowYInstruction, cb); table_instruction.DeleteBodyRows(); this.DrawPrintedOn(now, bf, cb); document.NewPage(); table_instruction.Rows.Add(headerRow); table_instruction.Rows.Add(lastRow); table_instruction.CalculateHeights(); rowYInstruction = startY; remainingRowToHeightInstruction = rowYInstruction - 5 - printedOnHeight - margin; allowedRow2HeightInstruction = remainingRowToHeightInstruction - printedOnHeight - margin; } } table_instruction.WriteSelectedRows(0, -1, 10, rowYInstruction, cb); #endregion #region RO Image var countImageRo = 0; byte[] roImage; if (viewModel.ImagesFile != null) { foreach (var index in viewModel.ImagesFile) { if (!string.IsNullOrEmpty(index)) { countImageRo++; } } } float rowYRoImage = rowYInstruction - table_instruction.TotalHeight - 5; float imageRoHeight; var remainingRowToHeightRoImage = rowYRoImage - 5 - printedOnHeight - margin; float allowedRow2HeightRoImage = rowYRoImage - printedOnHeight - margin; PdfPTable table_ro_image = null; if (countImageRo != 0) { table_ro_image = new PdfPTable(8); table_ro_image.DefaultCell.Border = Rectangle.NO_BORDER; float[] ro_widths = new float[8]; for (var i = 0; i < 8; i++) { ro_widths.SetValue(5f, i); } table_ro_image.SetWidths(ro_widths); table_ro_image.TotalWidth = 570f; for (var i = 0; i < viewModel.ImagesFile.Count; i++) { try { roImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ImagesFile[i])); } catch (Exception) { var webClient = new WebClient(); roImage = webClient.DownloadData("https://bateeqstorage.blob.core.windows.net/other/no-image.jpg"); } Image images = Image.GetInstance(imgb: roImage); var imageName = viewModel.ImagesName[i]; if (images.Width > 60) { float percentage = 0.0f; percentage = 60 / images.Width; images.ScalePercent(percentage * 100); } PdfPCell imageCell = new PdfPCell(images); imageCell.Border = 0; imageCell.Padding = 4; PdfPCell nameCell = new PdfPCell(); nameCell.Border = 0; nameCell.Padding = 4; nameCell.Phrase = new Phrase(imageName, normal_font); PdfPTable table_ro_name = new PdfPTable(1); table_ro_name.DefaultCell.Border = Rectangle.NO_BORDER; table_ro_name.AddCell(imageCell); table_ro_name.AddCell(nameCell); table_ro_name.CompleteRow(); table_ro_image.AddCell(table_ro_name); } table_ro_image.CompleteRow(); var tableROImageCurrentHeight = table_ro_image.TotalHeight; if (tableROImageCurrentHeight / remainingRowToHeightRoImage > 1) { if (tableROImageCurrentHeight / allowedRow2HeightRoImage > 1) { PdfPRow headerRow = table_ro_image.GetRow(0); PdfPRow lastRow = table_ro_image.GetRow(table_ro_image.Rows.Count - 1); table_ro_image.DeleteLastRow(); table_ro_image.WriteSelectedRows(0, -1, 10, rowYRoImage, cb); table_ro_image.DeleteBodyRows(); this.DrawPrintedOn(now, bf, cb); document.NewPage(); table_ro_image.Rows.Add(headerRow); table_ro_image.Rows.Add(lastRow); table_ro_image.CalculateHeights(); rowYRoImage = startY; remainingRowToHeightRoImage = rowYRoImage - 5 - printedOnHeight - margin; allowedRow2HeightRoImage = remainingRowToHeightRoImage - printedOnHeight - margin; } } imageRoHeight = table_ro_image.TotalHeight; table_ro_image.WriteSelectedRows(0, -1, 10, rowYRoImage, cb); } else { imageRoHeight = 0; } #endregion #region Signature (Bottom, Column 1.2) PdfPTable table_signature = new PdfPTable(4); table_signature.TotalWidth = 570f; float[] signature_widths = new float[] { 1f, 1f, 1f, 1f }; float rowYSignature = rowYRoImage - table_instruction.TotalHeight - 5; var remainingRowToHeightSignature = rowYSignature - 5 - printedOnHeight - margin; float allowedRow2HeightSignature = rowYSignature - printedOnHeight - margin; table_signature.SetWidths(signature_widths); PdfPCell cell_signature = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2, }; PdfPCell cell_signature_noted = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2, PaddingTop = 15 }; cell_signature.Phrase = new Phrase("Dibuat", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Kasie Merchandiser", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("R & D", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Ka Produksi", normal_font); table_signature.AddCell(cell_signature); //cell_signature.Phrase = new Phrase("Mengetahui", normal_font); //table_signature.AddCell(cell_signature); //cell_signature.Phrase = new Phrase("Menyetujui", normal_font); //table_signature.AddCell(cell_signature); var tableSignatureCurrentHeight = table_signature.TotalHeight; if (tableSignatureCurrentHeight / remainingRowToHeightSignature > 1) { if (tableSignatureCurrentHeight / allowedRow2HeightSignature > 1) { PdfPRow headerRow = table_signature.GetRow(0); PdfPRow lastRow = table_signature.GetRow(table_signature.Rows.Count - 1); table_signature.DeleteLastRow(); table_signature.WriteSelectedRows(0, -1, 10, rowYSignature, cb); table_signature.DeleteBodyRows(); this.DrawPrintedOn(now, bf, cb); document.NewPage(); table_signature.Rows.Add(headerRow); table_signature.Rows.Add(lastRow); table_signature.CalculateHeights(); rowYSignature = startY; remainingRowToHeightSignature = rowYSignature - 5 - printedOnHeight - margin; allowedRow2HeightSignature = remainingRowToHeightSignature - printedOnHeight - margin; } } cell_signature_noted.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature_noted); cell_signature_noted.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature_noted); cell_signature_noted.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature_noted); cell_signature_noted.Phrase = new Phrase("( )", normal_font); table_signature.AddCell(cell_signature_noted); //cell_signature_noted.Phrase = new Phrase("(Bekti Wahyuningsih)", normal_font); //table_signature.AddCell(cell_signature_noted); //cell_signature_noted.Phrase = new Phrase("(Michelle Tjokrosaputro)", normal_font); //table_signature.AddCell(cell_signature_noted); float table_signatureY = 0; if (table_ro_image != null) { table_signatureY = rowYRoImage - imageRoHeight - 5; } else { table_signatureY = rowYRoImage - 0 - 5; } table_signature.WriteSelectedRows(0, -1, 10, table_signatureY, cb); #endregion this.DrawPrintedOn(now, bf, cb); document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
protected void btnEnviar_Click(object sender, EventArgs e) { Usuario usuario = (Usuario)Session["usuario"]; string direccion_logo = "Av. Santa Rosa 4470, San Joaquin, Santiago - Tel: +56225526276"; //DateTime fecha = Convert.ToDateTime(txtFecha_.Value); Encabezado obj1 = new Encabezado(); TipoMoneda moneda = new TipoMoneda(); try { moneda.ID = Convert.ToInt32(txtMoneda.Value); moneda.Read(); obj1.Codigo_usuario = usuario.Usuario_; obj1.CondicionPago = txtCondicionesPago.Value; obj1.Contacto = txtContacto.Value; obj1.Correo = txtCorreo.Value; obj1.Entrega = txtEntrega.Value; obj1.Direccion = txtDireccion.Value; obj1.Estado = "Pendiente"; obj1.Observacion_estado = " "; //obj1.Fecha = fecha.ToString("dd/MM/yyyy"); obj1.Fecha = txtFecha_.Value; //obj1.Iva = Convert.ToInt32(txtIVA.Value); obj1.Tipo_moneda = moneda.Nombre; obj1.Iva = 0; obj1.Neto = Convert.ToDouble(txtNeto.Value.ToString().Replace(".", ",")); obj1.Razon_social = txtNombre.Value; obj1.Rut = txtRut.Value; obj1.Telefono = txtTelefono.Value; obj1.Total = Convert.ToDouble(txtTotal.Value.ToString().Replace(".", ",")); List <string> lista = ListValues(); obj1.Create(); string correlativo = obj1.Correlativo.ToString(); CreacionDetalle(correlativo, lista); byte[] bytesarray = null; using (var ms = new MemoryStream()) { using (var document = new Document(PageSize.A4, 20f, 20f, 45f, 35f)) //PageSize.A4, 20f, 20f, 65f, 35f--PageSize.A4, 20f, 20f, 75f, 35f { using (PdfWriter writer = PdfWriter.GetInstance(document, ms)) { document.Open(); PdfContentByte canvas = writer.DirectContent; writer.CompressionLevel = 0; canvas.SaveState(); canvas.BeginText(); canvas.MoveText(118, 773); canvas.SetFontAndSize(BaseFont.CreateFont(), 8); canvas.ShowText(direccion_logo); canvas.EndText(); canvas.RestoreState(); using (var strreader = new StringReader(HTMLPage(ListValues(), obj1, correlativo, usuario, moneda).ToString())) { var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/pdf/logo.png")); logo.ScaleAbsoluteWidth(450); logo.ScaleAbsoluteHeight(100); logo.SetAbsolutePosition(0, 750); document.Add(logo); //set factories HtmlPipelineContext htmlcontext = new HtmlPipelineContext(null); htmlcontext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); //set css ICSSResolver cssresolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssresolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/pdf/estilo.css"), true); //export IPipeline pipeline = new CssResolverPipeline(cssresolver, new HtmlPipeline(htmlcontext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var xmlparse = new XMLParser(true, worker); //var xmlparse = new XMLParser(); xmlparse.Parse(strreader); xmlparse.Flush(); } document.Close(); } } bytesarray = ms.ToArray(); ms.Close(); // clears all content output from the buffer stream Response.Clear(); // gets or sets the http mime type of the output stream. Response.ContentType = "application/pdf"; // adds an http header to the output stream Response.AddHeader("content-disposition", "attachment; filename=cotizacion_" + correlativo + ".pdf"); //gets or sets a value indicating whether to buffer output and send it after // the complete response is finished processing. Response.Buffer = true; // sets the cache-control header to one of the values of system.web.httpcacheability. Response.Cache.SetCacheability(HttpCacheability.NoCache); // writes a string of binary characters to the http output stream. it write the generated bytes . Response.BinaryWrite(bytesarray); // sends all currently buffered output to the client, stops execution of the // page, and raises the system.web.httpapplication.endrequest event. Response.Flush(); // sends all currently buffered output to the client. Response.SuppressContent = true; // gets or sets a value indicating whether to send http content to the client. HttpContext.Current.ApplicationInstance.CompleteRequest(); // causes asp.net to bypass all events and filtering in the http pipeline chain of execution and directly execute the endrequest event. // closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach. Response.Close(); } } catch (Exception ex) { ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true); } }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); if (writer.PageNumber != 1 && writer.PageNumber != 2 && writer.PageNumber != 3)// { iTextSharp.text.Font baseFontSmall = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(4); String text = "Page " + writer.PageNumber + " of "; //Add paging to header { cb.BeginText(); cb.SetFontAndSize(bf, 10); cb.SetTextMatrix(document.PageSize.GetRight(115), document.PageSize.GetTop(45)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 10); //Adds "12" in Page 1 of 12 cb.AddTemplate(headerTemplate, document.PageSize.GetRight(115) + len, document.PageSize.GetTop(45)); } ////Add paging to footer //{ // cb.BeginText(); // cb.SetFontAndSize(bf, 10); // cb.SetTextMatrix(document.PageSize.GetRight(115), document.PageSize.GetBottom(40)); // cb.ShowText(text); // cb.EndText(); // float len = bf.GetWidthPoint(text, 10); // cb.AddTemplate(footerTemplate, document.PageSize.GetRight(115) + len, document.PageSize.GetBottom(40)); //} PdfPCell pdfCellName = new PdfPCell(); if (formType != "") { pdfCellName = new PdfPCell(new Phrase("[" + CollegeCode + "] - " + PrintTime.ToShortDateString() + string.Format(" {0:t}", DateTime.Now), baseFontNormal)); } else { pdfCellName = new PdfPCell(new Phrase(PrintTime.ToString("dd-MMM-yyy") + string.Format(" {0:t}", DateTime.Now), baseFontNormal)); } //PdfPCell pdfCellDate = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString() + string.Format(" {0:t}", DateTime.Now), baseFontNormal)); PdfPCell pdfCellDate = new PdfPCell(new Phrase("", baseFontNormal)); //set the alignment of all cells and set border to 0 pdfCellDate.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCellDate.VerticalAlignment = Element.ALIGN_BOTTOM; pdfCellName.Border = 0; pdfCellDate.Border = 0; pdfCellName.Colspan = 3; //add all cells into PdfTable pdfTab.AddCell(pdfCellName); pdfTab.AddCell(pdfCellDate); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 60, document.PageSize.Height - 35, writer.DirectContent); //set pdfContent value PdfPTable pdfTabFooter = new PdfPTable(2); PdfPCell pdfCellLeft = new PdfPCell(); PdfPCell pdfCellRight = new PdfPCell(); //if (formType == "A-114") if (formType == "A-116") { pdfCellLeft = new PdfPCell(new Phrase("Name & Signature of Principal/Director", baseFontSmall)); pdfCellRight = new PdfPCell(new Phrase("Name & Signature of Chairman/Secretary", baseFontSmall)); } //if (formType == "A-414") if (formType == "A-416") { pdfCellRight = new PdfPCell(new Phrase("Total Number of corrections in page:_______", baseFontSmall)); pdfCellLeft = new PdfPCell(new Phrase("Name & Signature of the Committee Members", baseFontSmall)); } //set the alignment of all cells and set border to 0 pdfCellLeft.HorizontalAlignment = Element.ALIGN_CENTER; pdfCellRight.HorizontalAlignment = Element.ALIGN_CENTER; pdfCellLeft.VerticalAlignment = Element.ALIGN_TOP; pdfCellRight.VerticalAlignment = Element.ALIGN_TOP; pdfCellLeft.Border = 0; pdfCellRight.Border = 0; //add all cells into PdfTable pdfTabFooter.AddCell(pdfCellLeft); pdfTabFooter.AddCell(pdfCellRight); pdfTabFooter.TotalWidth = document.PageSize.Width - 80f; pdfTabFooter.WidthPercentage = 70; pdfTabFooter.WriteSelectedRows(0, -1, 60, document.PageSize.GetBottom(50), writer.DirectContent); //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(60, document.PageSize.Height - 50); cb.LineTo(document.PageSize.Width - 50, document.PageSize.Height - 50); cb.Stroke(); if (formType != "") { //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(60, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 50, document.PageSize.GetBottom(50)); cb.Stroke(); } } }
public static void GenerateAndSavePDF(string filePath, string mon, string tues, string weds, string thurs, string fri, string weekDate, string todayDate) { // Assign where to save the file here // You can also impliment something else and pass along the string file path string newFile = @"C:\Users\SOMEONE_IMPORTANT\" + $"{DateTime.Today.ToString("MM-dd-yyyy")}.pdf"; // open the reader PdfReader reader = new PdfReader(filePath); Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); // open the writer FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; // select the font properties BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetColorFill(BaseColor.DARK_GRAY); cb.SetFontAndSize(bf, 8); // Week ending date is this code block cb.BeginText(); string text = Form1.monDate.ToString("MM/dd"); // put the alignment and coordinates here cb.ShowTextAligned(1, text, 148, 365, 0); cb.EndText(); cb.BeginText(); text = weekDate; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 274, 478, 0); cb.EndText(); cb.BeginText(); text = Form1.tuesDate.ToString("MM/dd"); // put the alignment and coordinates here cb.ShowTextAligned(1, text, 148, 345, 0); cb.EndText(); cb.BeginText(); text = Form1.wedsDate.ToString("MM/dd"); // put the alignment and coordinates here cb.ShowTextAligned(1, text, 148, 320, 0); cb.EndText(); cb.BeginText(); text = Form1.thurDate.ToString("MM/dd"); // put the alignment and coordinates here cb.ShowTextAligned(1, text, 148, 298, 0); cb.EndText(); cb.BeginText(); text = Form1.friDate.ToString("MM/dd"); // put the alignment and coordinates here cb.ShowTextAligned(1, text, 148, 273, 0); cb.EndText(); cb.BeginText(); text = Form1.totalHours.ToString(); // put the alignment and coordinates here cb.ShowTextAligned(1, text, 448, 221, 0); cb.EndText(); cb.BeginText(); text = todayDate; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 440, 182, 0); cb.EndText(); // Regular Hours Code cb.BeginText(); text = mon; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 405, 365, 0); cb.EndText(); cb.BeginText(); text = tues; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 405, 345, 0); cb.EndText(); cb.BeginText(); text = weds; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 405, 320, 0); cb.EndText(); cb.BeginText(); text = thurs; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 405, 298, 0); cb.EndText(); cb.BeginText(); text = fri; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 405, 273, 0); cb.EndText(); // create the new page and add it to the pdf PdfImportedPage page = writer.GetImportedPage(reader, 1); cb.AddTemplate(page, 0, 0); // close the stream and boom goes the dynamite document.Close(); fs.Close(); writer.Close(); reader.Close(); }
public MemoryStream GeneratePdfTemplate(CostCalculationRetailViewModel viewModel) { BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); BaseFont bf_bold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); Font bold_font_8 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font font_9 = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9); DateTime now = DateTime.Now; Document document = new Document(PageSize.A4, 10, 10, 10, 10); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); PdfContentByte cb = writer.DirectContent; float margin = 10; float printedOnHeight = 10; float startY = 840 - margin; #region Header cb.BeginText(); cb.SetFontAndSize(bf, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. EFRATA RETAILINDO", 10, 820, 0); cb.SetFontAndSize(bf_bold, 12); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "COST CALCULATION RETAIL", 10, 805, 0); cb.EndText(); #endregion #region Top PdfPTable table_top = new PdfPTable(9); table_top.TotalWidth = 500f; float[] top_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1f, 0.1f, 2f }; table_top.SetWidths(top_widths); PdfPCell cell_top = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2 }; PdfPCell cell_colon = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE }; PdfPCell cell_top_keterangan = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2, Colspan = 7 }; cell_colon.Phrase = new Phrase(":", normal_font); cell_top.Phrase = new Phrase("RO", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.RO}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("BUYER", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Buyer.Name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("OL", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); double OLValue = viewModel.OL.Value ?? 0; string OL = OLValue > 0 ? OLValue.ToString() + " menit" : OLValue.ToString(); cell_top.Phrase = new Phrase($"{OL}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("ARTICLE", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Article}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("DELIVERY", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.DeliveryDate.ToString("dd MMMM yyyy")}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("OTL 1", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); double OTL1Value = viewModel.OTL1.Value ?? 0; string OTL1 = OTL1Value > 0 ? OTL1Value.ToString() + " detik" : OTL1Value.ToString(); cell_top.Phrase = new Phrase($"{OTL1}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("STYLE", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Style.name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("SIZE RANGE", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.SizeRange.Name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("OTL 2", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); double OTL2Value = viewModel.OTL2.Value ?? 0; string OTL2 = OTL2Value > 0 ? OTL2Value.ToString() + " detik" : OTL2Value.ToString(); cell_top.Phrase = new Phrase($"{OTL2}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("SEASON", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Season.name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("EFFICIENCY", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Efficiency.Value}%", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("OTL 3", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); double OTL3Value = viewModel.OTL3.Value ?? 0; string OTL3 = OTL3Value > 0 ? OTL3Value.ToString() + " detik" : OTL3Value.ToString(); cell_top.Phrase = new Phrase($"{OTL3}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("COUNTER", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Counter.name}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("RISK", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top.Phrase = new Phrase($"{viewModel.Risk}%", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("TOTAL SMV", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); double STD_HourValue = viewModel.SH_Cutting.Value + viewModel.SH_Finishing.Value + viewModel.SH_Sewing.Value; string STD_Hour = STD_HourValue > 0 ? STD_HourValue.ToString() : STD_HourValue.ToString(); cell_top.Phrase = new Phrase($"{STD_Hour}", normal_font); table_top.AddCell(cell_top); cell_top.Phrase = new Phrase("KETERANGAN", normal_font); table_top.AddCell(cell_top); table_top.AddCell(cell_colon); cell_top_keterangan.Phrase = new Phrase($"{viewModel.Description}", normal_font); table_top.AddCell(cell_top_keterangan); #endregion #region Draw Image float imageHeight; try { byte[] imageByte = Convert.FromBase64String(Base64.GetBase64File(viewModel.ImageFile)); Image image = Image.GetInstance(imgb: imageByte); if (image.Width > 60) { float percentage = 0.0f; percentage = 60 / image.Width; image.ScalePercent(percentage * 100); } imageHeight = image.ScaledHeight; float imageY = 800 - imageHeight; image.SetAbsolutePosition(520, imageY); cb.AddImage(image, inlineImage: true); } catch (Exception) { imageHeight = 0; } #endregion #region Draw Top float row1Y = 800; table_top.WriteSelectedRows(0, -1, 10, row1Y, cb); #endregion #region Detail (Bottom, Column 1.2) PdfPTable table_detail = new PdfPTable(2); table_detail.TotalWidth = 280f; float[] detail_widths = new float[] { 1f, 1f }; table_detail.SetWidths(detail_widths); PdfPCell cell_detail = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5, Rowspan = 4 }; double total = Convert.ToDouble(viewModel.OL.CalculatedValue + viewModel.OTL1.CalculatedValue + viewModel.OTL2.CalculatedValue + viewModel.OTL3.CalculatedValue); cell_detail.Phrase = new Phrase( "OL".PadRight(22) + ": " + viewModel.OL.CalculatedValue + Environment.NewLine + Environment.NewLine + "OTL 1".PadRight(20) + ": " + viewModel.OTL1.CalculatedValue + Environment.NewLine + Environment.NewLine + "OTL 2".PadRight(20) + ": " + viewModel.OTL2.CalculatedValue + Environment.NewLine + Environment.NewLine + "OTL 3".PadRight(20) + ": " + viewModel.OTL3.CalculatedValue + Environment.NewLine + Environment.NewLine + "Total".PadRight(22) + ": " + total + Environment.NewLine , normal_font); table_detail.AddCell(cell_detail); cell_detail = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_BOTTOM, Padding = 5 }; cell_detail.Phrase = new Phrase("HPP", normal_font); table_detail.AddCell(cell_detail); cell_detail = new PdfPCell() { Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5 }; cell_detail.Phrase = new Phrase(Number.ToRupiah(viewModel.HPP), font_9); table_detail.AddCell(cell_detail); cell_detail = new PdfPCell() { Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_BOTTOM, Padding = 5 }; cell_detail.Phrase = new Phrase("Wholesale Price: HPP X 2.20", normal_font); table_detail.AddCell(cell_detail); cell_detail = new PdfPCell() { Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5 }; cell_detail.Phrase = new Phrase(Number.ToRupiah(viewModel.WholesalePrice), font_9); table_detail.AddCell(cell_detail); #endregion #region Signature (Bottom, Column 1.2) PdfPTable table_signature = new PdfPTable(3); table_signature.TotalWidth = 280f; float[] signature_widths = new float[] { 1f, 1f, 1f }; table_signature.SetWidths(signature_widths); PdfPCell cell_signature = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; cell_signature.Phrase = new Phrase("Mengetahui,", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Menyetujui,", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Ka. Sie Merchandiser", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Creative Director", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("President Director", normal_font); table_signature.AddCell(cell_signature); string signatureArea = string.Empty; for (int i = 0; i < 5; i++) { signatureArea += Environment.NewLine; } cell_signature.Phrase = new Phrase(signatureArea, normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase(signatureArea, normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase(signatureArea, normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Anita Purnamaningrum", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Ari Seputra", normal_font); table_signature.AddCell(cell_signature); cell_signature.Phrase = new Phrase("Michelle Tjokrosaputro", normal_font); table_signature.AddCell(cell_signature); #endregion #region Price (Bottom, Column 2) PdfPTable table_price = new PdfPTable(5); table_price.TotalWidth = 280f; float[] price_widths = new float[] { 1.6f, 3f, 3f, 4f, 1f }; table_price.SetWidths(price_widths); PdfPCell cell_price_center = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_price_left = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_price_right = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; cell_price_center.Phrase = new Phrase("KET (X)", bold_font); table_price.AddCell(cell_price_center); cell_price_center.Phrase = new Phrase("HARGA (Rp)", bold_font); table_price.AddCell(cell_price_center); cell_price_center.Phrase = new Phrase("PEMBULATAN HARGA (Rp)", bold_font); table_price.AddCell(cell_price_center); cell_price_center.Phrase = new Phrase("KETERANGAN", bold_font); table_price.AddCell(cell_price_center); cell_price_center.Phrase = new Phrase("", bold_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed20), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding20), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding20") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.1", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed21), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding21), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding21") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.2", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed22), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding22), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding22") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.3", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed23), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding23), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding23") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.4", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed24), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding24), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding24") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.5", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed25), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding25), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding25") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.6", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed26), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding26), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding26") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.7", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed27), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding27), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding27") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.8", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed28), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding28), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding28") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("2.9", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed29), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding29), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding29") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("3.0", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed30), normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding30), normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding30") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); cell_price_left.Phrase = new Phrase("Others", normal_font); table_price.AddCell(cell_price_left); cell_price_right.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_right); cell_price_right.Phrase = new Phrase(viewModel.RoundingOthers > 0 ? Number.ToRupiahWithoutSymbol(viewModel.RoundingOthers) : "", normal_font); table_price.AddCell(cell_price_right); cell_price_left.Phrase = new Phrase("", normal_font); table_price.AddCell(cell_price_left); cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("RoundingOthers") ? "*" : "", normal_font); table_price.AddCell(cell_price_center); #endregion #region Cost Calculation Material PdfPTable table_ccm = new PdfPTable(7); table_ccm.TotalWidth = 570f; float[] ccm_widths = new float[] { 1.25f, 3.5f, 4f, 9f, 3f, 4f, 4f }; table_ccm.SetWidths(ccm_widths); PdfPCell cell_ccm_center = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_ccm_left = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; PdfPCell cell_ccm_right = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; cell_ccm_center.Phrase = new Phrase("NO", bold_font); table_ccm.AddCell(cell_ccm_center); cell_ccm_center.Phrase = new Phrase("CATEGORIES", bold_font); table_ccm.AddCell(cell_ccm_center); cell_ccm_center.Phrase = new Phrase("MATERIALS", bold_font); table_ccm.AddCell(cell_ccm_center); cell_ccm_center.Phrase = new Phrase("DESCRIPTION", bold_font); table_ccm.AddCell(cell_ccm_center); cell_ccm_center.Phrase = new Phrase("QUANTITY", bold_font); table_ccm.AddCell(cell_ccm_center); cell_ccm_center.Phrase = new Phrase("RP. PTC/PC", bold_font); table_ccm.AddCell(cell_ccm_center); cell_ccm_center.Phrase = new Phrase("RP. TOTAL", bold_font); table_ccm.AddCell(cell_ccm_center); double Total = 0; float row1Height = imageHeight > table_top.TotalHeight ? imageHeight : table_top.TotalHeight; float row2Y = row1Y - row1Height - 10; float calculatedHppHeight = 7; float row3LeftHeight = table_detail.TotalHeight + 5 + table_signature.TotalHeight; float row3RightHeight = table_price.TotalHeight; float row3Height = row3LeftHeight > row3RightHeight ? row3LeftHeight : row3RightHeight; float remainingRow2Height = row2Y - 10 - row3Height - printedOnHeight - margin; float allowedRow2Height = row2Y - printedOnHeight - margin; for (int i = 0; i < viewModel.CostCalculationRetail_Materials.Count; i++) { cell_ccm_center.Phrase = new Phrase((i + 1).ToString(), normal_font); table_ccm.AddCell(cell_ccm_center); cell_ccm_left.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Category.SubCategory != null ? String.Format("{0} - {1}", viewModel.CostCalculationRetail_Materials[i].Category.Name, viewModel.CostCalculationRetail_Materials[i].Category.SubCategory) : viewModel.CostCalculationRetail_Materials[i].Category.Name, normal_font); table_ccm.AddCell(cell_ccm_left); cell_ccm_left.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Material.Name, normal_font); table_ccm.AddCell(cell_ccm_left); cell_ccm_left.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Description, normal_font); table_ccm.AddCell(cell_ccm_left); cell_ccm_right.Phrase = new Phrase(String.Format("{0} {1}", viewModel.CostCalculationRetail_Materials[i].Quantity, viewModel.CostCalculationRetail_Materials[i].UOMQuantity.Name), normal_font); table_ccm.AddCell(cell_ccm_right); cell_ccm_right.Phrase = new Phrase(String.Format("{0}/{1}", Number.ToRupiahWithoutSymbol(viewModel.CostCalculationRetail_Materials[i].Price), viewModel.CostCalculationRetail_Materials[i].UOMPrice.Name), normal_font); table_ccm.AddCell(cell_ccm_right); cell_ccm_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.CostCalculationRetail_Materials[i].Total), normal_font); table_ccm.AddCell(cell_ccm_right); Total += viewModel.CostCalculationRetail_Materials[i].Total; float currentHeight = table_ccm.TotalHeight; if (currentHeight / remainingRow2Height > 1) { if (currentHeight / allowedRow2Height > 1) { PdfPRow headerRow = table_ccm.GetRow(0); PdfPRow lastRow = table_ccm.GetRow(table_ccm.Rows.Count - 1); table_ccm.DeleteLastRow(); table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb); table_ccm.DeleteBodyRows(); this.DrawPrintedOn(now, bf, cb); document.NewPage(); table_ccm.Rows.Add(headerRow); table_ccm.Rows.Add(lastRow); table_ccm.CalculateHeights(); row2Y = startY; remainingRow2Height = row2Y - 10 - row3Height - printedOnHeight - margin; allowedRow2Height = row2Y - printedOnHeight - margin; } } } cell_ccm_right = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2, Colspan = 6 }; cell_ccm_right.Phrase = new Phrase("TOTAL", bold_font_8); table_ccm.AddCell(cell_ccm_right); cell_ccm_right = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2 }; cell_ccm_right.Phrase = new Phrase(Number.ToRupiah(Total), bold_font_8); table_ccm.AddCell(cell_ccm_right); #endregion #region Draw Middle and Bottom table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb); float row3Y = row2Y - table_ccm.TotalHeight - 10; float remainingRow3Height = row3Y - printedOnHeight - margin; if (remainingRow3Height < row3Height) { this.DrawPrintedOn(now, bf, cb); row3Y = startY; document.NewPage(); } #region Calculated HPP float calculatedHppY = row3Y - calculatedHppHeight; cb.BeginText(); cb.SetFontAndSize(bf, 8); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "KALKULASI HPP: (OL + OTL1 + OTL2 + FABRIC + ACC) + ((OL + OTL1 + OTL2 + FABRIC + ACC) * Risk)", 10, calculatedHppY, 0); cb.EndText(); #endregion float table_detailY = calculatedHppY - 5; table_detail.WriteSelectedRows(0, -1, 10, table_detailY, cb); float table_signatureY = table_detailY - row3Height + table_signature.TotalHeight; table_signature.WriteSelectedRows(0, -1, 10, table_signatureY, cb); table_price.WriteSelectedRows(0, -1, 300, table_detailY, cb); this.DrawPrintedOn(now, bf, cb); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
/// <summary> /// Crea PDF para las Cargas de las Sucursales /// </summary> /// <param name="carga">Objeto CargaSucursal con los datos de la Carga de la Sucursal</param> /// <summary> /// Crea PDF para las Cargas de Sucursales /// </summary> /// <param name="carga">Objeto ManifiestoSucursal con los datos de la Carga de la Sucursal</param> public void CrearPDFSucursal(ManifiestoSucursalCarga man) //Abre crear PDF Sucursal { CargaSucursal carga = _carga; DateTime hoy = DateTime.Today; string actual = hoy.ToString("dd/MM/yyyy"); string destinopdf = @"\\10.120.131.100\Manifiestos\SUC-" + man.ID.ToString() + ".pdf"; //DEFINE NOMBRE Y UBICACION DEL PDF QUE SE DESEA CREAR Stream output = new FileStream(destinopdf, FileMode.Create, FileAccess.Write); string plantilla = @"\\10.120.131.100\Releases\manifiesto5.pdf"; //DEFINE LA UBICACION Y EL NOMBRE DE LA PLANTILLA A USAR TipoCambio tip = null; tip = _mantenimiento.obtenerTipoCambio(dtpFecha.Value); int tipocambio = (int)tip.Venta; int tipocambioeuros = (int)tip.VentaEuros; PdfReader readerBicycle = null; iTextSharp.text.Rectangle pagesize = new iTextSharp.text.Rectangle(504, 580); Document documento = new Document(pagesize); FileStream theFile = new FileStream(plantilla, FileMode.Open, FileAccess.Read); PdfWriter writer = PdfWriter.GetInstance(documento, output); writer.SetEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.STRENGTH40BITS); documento.Open(); readerBicycle = new PdfReader(theFile); PdfTemplate background = writer.GetImportedPage(readerBicycle, 1); documento.NewPage(); string receptor = ""; string emisor = ""; iTextSharp.text.Image pic = null; iTextSharp.text.Image pic2 = null; if (carga.Tripulacion == null) { carga.Tripulacion = new Tripulacion(); } string colaborador_recibo = ""; if (carga.ColaboradorRecibidoBoveda != null) { colaborador_recibo = carga.ColaboradorRecibidoBoveda.ID.ToString(); } if (File.Exists(@"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion" + carga.Tripulacion.ID.ToString() + "-colaboradorentrega" + carga.Tripulacion.Portavalor.ID.ToString() + "-colaboradorrecibe" + colaborador_recibo + "-fecha" + carga.Fecha_asignada.Year.ToString() + carga.Fecha_asignada.Month.ToString() + carga.Fecha_asignada.Day.ToString("00") + ".jpg")) { if (carga.EntregaBovedaSucursal == EntregaRecibo.Entregas) { receptor = @"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion" + carga.Tripulacion.ID.ToString() + "-colaboradorrecibe" + carga.Tripulacion.Portavalor.ID.ToString() + "-colaboradorentrega" + colaborador_recibo + "-fecha" + carga.Fecha_asignada.Year.ToString() + carga.Fecha_asignada.Month.ToString("00") + carga.Fecha_asignada.Day.ToString("00") + ".jpg"; emisor = @"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion" + carga.Tripulacion.ID.ToString() + "-colaboradorrecibe" + colaborador_recibo + "-colaboradorentrega" + carga.Tripulacion.Portavalor.ID.ToString() + "-fecha" + carga.Fecha_asignada.Year.ToString() + carga.Fecha_asignada.Month.ToString("00") + carga.Fecha_asignada.Day.ToString("00") + ".jpg"; } else { receptor = @"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion" + carga.Tripulacion.ID.ToString() + "-colaboradorrecibe" + carga.Tripulacion.Portavalor.ID.ToString() + "-colaboradorentrega" + colaborador_recibo + "-fecha" + carga.Fecha_asignada.Year.ToString() + carga.Fecha_asignada.Month.ToString("00") + carga.Fecha_asignada.Day.ToString("00") + ".jpg"; emisor = @"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion" + carga.Tripulacion.ID.ToString() + "-colaboradorrecibe" + colaborador_recibo + "-colaboradorentrega" + carga.Tripulacion.Portavalor.ID.ToString() + "-fecha" + carga.Fecha_asignada.Year.ToString() + carga.Fecha_asignada.Month.ToString("00") + carga.Fecha_asignada.Day.ToString("00") + ".jpg"; } pic = iTextSharp.text.Image.GetInstance(receptor); pic2 = iTextSharp.text.Image.GetInstance(emisor); pic.ScaleAbsolute(75, 45); pic.SetAbsolutePosition(411, 440); documento.Add(pic); // receptor pic2.ScaleAbsolute(75, 35); pic2.SetAbsolutePosition(411, 120); documento.Add(pic2); } _pcb = writer.DirectContentUnder; _pcb.AddTemplate(background, 0, 0); _pcb = writer.DirectContent; _pcb.BeginText(); //pic2.ScaleAbsolute(75, 45); //pic2.SetAbsolutePosition(411, 330); //documento.Add(pic2); //_pcb = writer.DirectContentUnder; //_pcb.AddTemplate(background, 0, 0); //_pcb = writer.DirectContent; //_pcb.BeginText(); TipoCambio t = _mantenimiento.obtenerTipoCambio(dtpFecha.Value); //_pcno me diab = writer.DirectContentUnder; //_pcb.AddTemplate(background, 0, 0); //_pcb = writer.DirectContent; //_pcb.BeginText(); SetFontBarCode(8); //ESTABLECE LA FUENTE E IMPRIME CON LA FUENTE BARCODE HASTA SER CAMBIADA PrintText("*" + man.ID.ToString() + "*", 335, 561); //Imprime codigo de barras SetFont(13); PrintText("No: SUC-" + man.ID.ToString(), 335, 550); //Imprime numero de manifiesto SetFont(8); //CAMBIAMOS LA FUENTE //montoLetrasPdf(montoenletras); //Imprime monto total en letras y valida el tamaño PrintText(t.Venta.ToString("N0") + "/" + t.VentaEuros.ToString("N0"), 300, 525); //Imprime tipo de cambio PrintText(carga.Cartuchos.Count.ToString(), 360, 525); //Cantidad depositos PrintText("1", 440, 525); //Imprime cantidad de manifiestos //LADO IZQUIERDO if (carga.EntregaBovedaSucursal == EntregaRecibo.Entregas) { PrintText("SERVICIO BANCARIO", 90, 490); //Origen de los fondos PrintText(carga.Sucursal.Nombre, 59, 465); //Origen de los fondos //PrintText("Centro de Dist. Cipreses", 59, 440); PrintText(carga.Sucursal.Provincia.ToString(), 44, 416); //Origen de los fondos PrintText(carga.Sucursal.Provincia.ToString(), 175, 417); //Provincia PrintText(dtpFecha.Value.ToShortDateString(), 230, 384); //Fecha de Entrega if (carga.Colaborador_verificador != null) { PrintText(carga.Colaborador_verificador.ToString(), 19, 384); //Nombre de Persona que preparó cargamento } if (carga.Tripulacion.Portavalor != null) { PrintText("BAC SAN JOSE", 52, 354);//PrintText(carga.Tripulacion.Portavalor.ToString(), 52, 354); //Entregado a } if (carga.Sucursal.Direccion != null) { PrintText(carga.Sucursal.Direccion, 59, 440); //Origen de los fondos } PrintText("Centro de Dist. Cipreses", 45, 330); // Direccion PrintText("CURRIDABAT", 45, 307); // Ciudad PrintText("SAN JOSE", 178, 307); //Provincia if (carga.Sucursal != null) { PrintText("CURRIDABAT", 201, 353); //Oficinas //PrintText("Centro de Dist. Cipreses", 323, 60); //DIRECCION //PrintText("SAN JOSE", 323, 228); //Provincia } } else { if (carga.EntregaBovedaSucursal == EntregaRecibo.Pedidos) { PrintText("SERVICIO BANCARIO", 90, 490); //Origen de los fondos PrintText("BAC San José", 59, 465); //Origen de los fondos PrintText("Centro de Dist. Cipreses", 59, 440); //Origen de los fondos PrintText("CURRIDABAT", 44, 416); //Origen de los fondos //PrintText("SAN JOSE", 175, 417); //Provincia PrintText(dtpFecha.Value.ToShortDateString(), 230, 384); //Fecha de Entrega PrintText(carga.Sucursal.Provincia.ToString(), 175, 417); //Provincia if (carga.Colaborador_verificador != null) { PrintText(carga.Colaborador_verificador.ToString(), 19, 384); //Nombre de Persona que preparó cargamento } if (carga.Tripulacion.Portavalor != null) { PrintText("BAC SAN JOSE", 52, 354);//PrintText(carga.Tripulacion.Portavalor.ToString(), 52, 354); //Entregado a } if (carga.Sucursal.Direccion != null) { PrintText(carga.Sucursal.Direccion.ToString(), 45, 330); // Direccion } PrintText(carga.Sucursal.Provincia.ToString(), 178, 307); //Provincia PrintText(carga.Sucursal.Provincia.ToString(), 45, 307); //Ciudad if (carga.Sucursal != null) { PrintText(carga.Sucursal.Nombre, 201, 353); //Oficinas } } } //MARCHAMOS BT BULTOS Y MONTO int bultos = 0; //if (carga.Cartuchos.Count > 5 || carga.Cartuchos == null) //{ int fila = 276; decimal montocol = 0; decimal montodol = 0; decimal montoeur = 0; string monto_final_letras = ""; foreach (Bolsa b in man.ListaBolsas) { Bolsa copia = b; montocol = 0; montodol = 0; montoeur = 0; foreach (BolsaMontosSucursales mont in copia.Cartuchos) { if (mont.Denominacion.Moneda == Monedas.Colones) { montocol = montocol + mont.Cantidad_asignada; } if (mont.Denominacion.Moneda == Monedas.Dolares) { montodol = montodol + mont.Cantidad_asignada; } if (mont.Denominacion.Moneda == Monedas.Euros) { montoeur = montoeur + mont.Cantidad_asignada; } } if (montocol > 0) { PrintText(("CRC " + montocol.ToString("N2")), 148, fila); /*MONTO colones*/ PrintText("B", 86, fila); /*BULTOS*/ PrintText("1", 110, fila); /*BT*/ PrintText(copia.SerieBolsa, 20, fila); /*Numero de Bolsa*/ fila = fila - 20; } if (montodol > 0) { PrintText(("USD " + montodol.ToString("N2")), 148, fila); /*MONTO colones*/ PrintText("B", 86, fila); /*BULTOS*/ PrintText("1", 110, fila); /*BT*/ PrintText(copia.SerieBolsa, 20, fila); /*Numero de Bolsa*/ fila = fila - 20; } if (montoeur > 0) { PrintText(("EUR " + montoeur.ToString("N2")), 148, fila); /*MONTO colones*/ PrintText("B", 86, fila); /*BULTOS*/ PrintText("1", 110, fila); /*BT*/ PrintText(copia.SerieBolsa, 20, fila); /*Numero de Bolsa*/ fila = fila - 20; } // Muestra el valor total del manifiesto. //PrintText(("CRC " + (montocol + (montodol * tipocambio) + (montoeur * tipocambioeuros)).ToString("N2")), 152, 33); //Realiza la suma de Carga en colones mas la Carga de dolares en colones //string montototal = ""; //montototal = Convert.ToInt64(montocol + (montodol * tipocambio) + (montoeur * tipocambioeuros)).ToString(); //Conviete el gran total en letras. //if (montototal != "0") //{ // montoenletras = _coordinacion.convertirMontoaLetras(montototal) + " DE COLONES"; //} } decimal montito_total = 0; foreach (Bolsa b in man.ListaBolsas) { foreach (BolsaMontosSucursales bol in b.Cartuchos) { if (bol.Denominacion.Moneda == Monedas.Dolares) { montito_total = montito_total + (bol.Cantidad_asignada * tipocambio); } if (bol.Denominacion.Moneda == Monedas.Euros) { montito_total = montito_total + (bol.Cantidad_asignada * tipocambioeuros); } if (bol.Denominacion.Moneda == Monedas.Colones) { montito_total = montito_total + bol.Cantidad_asignada; } } } string montito_total_letras = _coordinacion.convertirMontoaLetras(montito_total.ToString()); string monto = montito_total_letras + " DE COLONES"; //Imprime Gran Total Monto en Letras en el pdf if (monto.Length > 80) { PrintText(monto.Substring(0, 28), 18, 523); PrintText(monto.Substring(68, monto.Length - 28), 20, 521); } else { PrintText(monto, 18, 523); } // Muestra total manifiesto PrintText(("CRC " + montito_total.ToString("N2")), 152, 33); //LADO DERECHO if (carga.Tripulacion != null) { PrintText(carga.Tripulacion.Portavalor.ToString(), 303, 486); //Nombre portavalor recibe } else { PrintText("", 303, 486); //Nombre portavalor recibe } PrintText(carga.Ruta.ToString(), 361, 465); //Ruta PrintText(man.ListaBolsas.Count.ToString(), 311, 465); PrintText(carga.Hora_inicio.ToShortTimeString(), 305, 420); PrintText(carga.Hora_finalizacion.ToShortTimeString(), 358, 420); PrintText(dtpFecha.Value.ToShortDateString(), 333, 440); //Fecha //Obtiene el nombre del portavalor. _coordinacion.listarPortavalorPorCargaSucursal(ref carga); if (carga.ColaboradorRecibidoBoveda != null) { PrintText((carga.ColaboradorRecibidoBoveda + " " + carga.ColaboradorRecibidoBoveda.Identificacion), 320, 632); PrintText((carga.ColaboradorRecibidoBoveda + " " + carga.ColaboradorRecibidoBoveda.Identificacion), 320, 578); } else { PrintText("", 320, 578); PrintText("", 320, 632); } //PrintText(carga.Ruta.ToString(), 369, 175); //Ruta //PrintText(man.ListaBolsas.Count.ToString(), 317, 175);// Bultos //PrintText(carga.Fecha_asignada.ToShortDateString(), 416, 175);// Fecha //////////////////////////////////////Quitar el número de ATM 08/04/2014/////////////////////////////////////////////////////// PrintText(carga.Observaciones, 325, 450); _pcb.EndText(); writer.Flush(); if (readerBicycle == null) { readerBicycle.Close(); } documento.Close(); //Cierra crear PDF Sucursal } //Cierra crear PDF Sucursales
/// <summary> /// 合并文档 /// </summary> /// <param name="outputStream"></param> public void Merge(Stream outputStream) { if (outputStream == null || !outputStream.CanWrite) { throw new ArgumentException("OutputStream es nulo o no se puede escribir en éste."); } Document newDocument = null; try { newDocument = new Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, outputStream); newDocument.Open(); PdfContentByte pdfContentByte = pdfWriter.DirectContent; if (EnablePagination) { documents.ForEach(delegate(PdfFile doc) { totalPages += doc.PdfReader.NumberOfPages; }); } int currentPage = 1; for (int i = 0; i < documents.Count; ++i) { PdfReader pdfReader = documents[i].PdfReader; for (int page = 1; page <= pdfReader.NumberOfPages; page++) { PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page); // 按照原有尺寸设置纸张大小 newDocument.SetPageSize(importedPage.BoundingBox); if (page == 1) { Chapter chapter1 = new Chapter(documents[i].Name, i + 1); chapter1.BookmarkTitle = documents[i].Name; // invisible it. but not to set 0 which will cause error chapter1.Title.Font.Size = 0.01f; newDocument.Add(chapter1); } else { newDocument.NewPage(); } pdfContentByte.AddTemplate(importedPage, 0, 0); if (EnablePagination) { pdfContentByte.BeginText(); pdfContentByte.SetFontAndSize(baseFont, 9); pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, string.Format("{0} de {1}", currentPage++, totalPages), 520, 5, 0); pdfContentByte.EndText(); } } } } finally { outputStream.Flush(); if (newDocument != null) { newDocument.Close(); } outputStream.Close(); } }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { String fullCode = code; if (generateChecksum && checksumText) { fullCode = CalculateChecksum(code); } if (!startStopText) { fullCode = fullCode.Substring(1, fullCode.Length - 2); } float fontX = 0; if (font != null) { fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } byte[] bars = GetBarsCodabar(generateChecksum ? CalculateChecksum(code) : code); int wide = 0; for (int k = 0; k < bars.Length; ++k) { wide += (int)bars[k]; } int narrow = bars.Length - wide; float fullWidth = x * (narrow + wide * n); float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) { barStartX = fontX - fullWidth; } else { textStartX = fullWidth - fontX; } break; default: if (fontX > fullWidth) { barStartX = (fontX - fullWidth) / 2; } else { textStartX = (fullWidth - fontX) / 2; } break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) { textStartY = barHeight - baseline; } else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } bool print = true; if (barColor != null) { cb.SetColorFill(barColor); } for (int k = 0; k < bars.Length; ++k) { float w = (bars[k] == 0 ? x : x * n); if (print) { cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) { cb.SetColorFill(textColor); } cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return(BarcodeSize); }
protected void btnImagesAndGraphics_Click(object sender, EventArgs e) { try { using (System.IO.FileStream fs = new FileStream(Server.MapPath("pdf") + "\\" + "PDF with graphics and images.pdf", FileMode.Create)) { Document document = new Document(PageSize.A4, 25, 25, 30, 30); PdfWriter writer = PdfWriter.GetInstance(document, fs); // Add meta information to the document document.AddAuthor("Mikael Blomquist"); document.AddCreator("Sample application using iTestSharp"); document.AddKeywords("PDF tutorial education"); document.AddSubject("Document subject - Describing the steps creating a PDF document"); document.AddTitle("The document title - PDF creation using iTextSharp"); // Open the document to enable you to write to the document document.Open(); // Makes it possible to add text to a specific place in the document using // a X & Y placement syntax. PdfContentByte cb = writer.DirectContent; cb.SetFontAndSize(f_cb, 16); // First we must activate writing cb.BeginText(); // Write text at a certain position cb.SetTextMatrix(25, 810); // Left, Top cb.ShowText("Hello World"); // Change the font and the size cb.SetFontAndSize(f_cn, 9); // Here is to write text that are aligned cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "This text is left aligned", 200, 800, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "This text is right aligned", 200, 788, 0); cb.EndText(); // Add an image to a fixed position from a URL iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("http://www.c-sharpcorner.com/App_Themes/CSharp/Images/CSSiteLogo.gif"); img.SetAbsolutePosition(50, 647); img.ScaleAbsolute(216, 70); cb.AddImage(img); // Move and resize the image img.SetAbsolutePosition(385, 733); img.ScalePercent(50); cb.AddImage(img); // Add an image to a fixed position from disk iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(Server.MapPath("img.png")); png.SetAbsolutePosition(200, 450); cb.AddImage(png); // Draw a line by setting the line width and position cb.SetLineWidth(0f); cb.MoveTo(30, 650); cb.LineTo(570, 650); cb.Stroke(); // Draw a rectangle cb.Rectangle(350, 550, 150, 150); cb.Stroke(); // Close the document document.Close(); writer.Close(); fs.Close(); lblMsg.Text = "Document saved to the pdf folder."; } } catch (Exception rror) { lblMsg.Text = rror.Message; } }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) { string fullCode = code; float fontX = 0; string bCode = code; if (extended) { bCode = GetCode39Ex(code); } if (font != null) { if (generateChecksum && checksumText) { fullCode += GetChecksum(bCode); } if (startStopText) { fullCode = "*" + fullCode + "*"; } fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } if (generateChecksum) { bCode += GetChecksum(bCode); } int len = bCode.Length + 2; float fullWidth = len * (6 * x + 3 * x * n) + (len - 1) * x; float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) { barStartX = fontX - fullWidth; } else { textStartX = fullWidth - fontX; } break; default: if (fontX > fullWidth) { barStartX = (fontX - fullWidth) / 2; } else { textStartX = (fullWidth - fontX) / 2; } break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) { textStartY = barHeight - baseline; } else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } byte[] bars = GetBarsCode39(bCode); bool print = true; if (barColor != null) { cb.SetColorFill(barColor); } for (int k = 0; k < bars.Length; ++k) { float w = (bars[k] == 0 ? x : x * n); if (print) { cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) { cb.SetColorFill(textColor); } cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return(this.BarcodeSize); }
protected void btnCreateExampleInvoice_Click(object sender, EventArgs e) { try { // Read the sample XML file using the contructor, giving the file path Invoice invoice = new Invoice(Server.MapPath("invoices") + "\\invoice_123456.xml"); // Create references for each of the on-row tables to make it easier to access the values // in the table using syntax like this: drHead["invoiceId"].ToString() DataRow drHead = invoice.GetInvoiceHeader().Rows[0]; DataRow drTotal = invoice.GetInvoiceTotal().Rows[0]; DataRow drPayee = invoice.GetInvoicePayeeInfo().Rows[0]; using (System.IO.FileStream fs = new FileStream(Server.MapPath("invoices") + "\\" + "Invoice_" + drHead["invoiceId"].ToString() + ".pdf", FileMode.Create)) { Document document = new Document(PageSize.A4, 25, 25, 30, 1); PdfWriter writer = PdfWriter.GetInstance(document, fs); // Add meta information to the document document.AddAuthor("Mikael Blomquist"); document.AddCreator("Sample application using iTestSharp"); document.AddKeywords("PDF tutorial education"); document.AddSubject("Describing the steps creating a PDF document"); document.AddTitle("PDF creation using iTextSharp - Sample invoice"); // Open the document to enable you to write to the document document.Open(); // Makes it possible to add text to a specific place in the document using // a X & Y placement syntax. PdfContentByte cb = writer.DirectContent; // Add a footer template to the document cb.AddTemplate(PdfFooter(cb, drPayee), 30, 1); // Add a logo to the invoice iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(Server.MapPath("mbase_emc2.png")); png.ScaleAbsolute(200, 55); png.SetAbsolutePosition(40, 750); cb.AddImage(png); // First we must activate writing cb.BeginText(); // First we write out the header information // Start with the invoice type header writeText(cb, drHead["invoiceType"].ToString(), 350, 820, f_cb, 14); // HEader details; invoice number, invoice date, due date and customer Id writeText(cb, "Invoice No", 350, 800, f_cb, 10); writeText(cb, drHead["invoiceId"].ToString(), 420, 800, f_cn, 10); writeText(cb, "Invoice date", 350, 788, f_cb, 10); writeText(cb, drHead["invoiceDate"].ToString(), 420, 788, f_cn, 10); writeText(cb, "Due date", 350, 776, f_cb, 10); writeText(cb, drHead["dueDate"].ToString(), 420, 776, f_cn, 10); writeText(cb, "Customer", 350, 764, f_cb, 10); writeText(cb, drHead["customerId"].ToString(), 420, 764, f_cn, 10); // Delivery address details int left_margin = 40; int top_margin = 720; writeText(cb, "Delivery address", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["delCustomerName"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, drHead["delAddress1"].ToString(), left_margin, top_margin - 24, f_cn, 10); writeText(cb, drHead["delAddress2"].ToString(), left_margin, top_margin - 36, f_cn, 10); writeText(cb, drHead["delAddress3"].ToString(), left_margin, top_margin - 48, f_cn, 10); writeText(cb, drHead["delZipcode"].ToString(), left_margin, top_margin - 60, f_cn, 10); writeText(cb, drHead["delCity"].ToString() + ", " + drHead["delCountry"].ToString(), left_margin + 65, top_margin - 60, f_cn, 10); // Invoice address left_margin = 350; writeText(cb, "Invoice address", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["invCustomerName"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, drHead["invAddress1"].ToString(), left_margin, top_margin - 24, f_cn, 10); writeText(cb, drHead["invAddress2"].ToString(), left_margin, top_margin - 36, f_cn, 10); writeText(cb, drHead["invAddress3"].ToString(), left_margin, top_margin - 48, f_cn, 10); writeText(cb, drHead["invZipcode"].ToString(), left_margin, top_margin - 60, f_cn, 10); writeText(cb, drHead["invCity"].ToString() + ", " + drHead["invCountry"].ToString(), left_margin + 65, top_margin - 60, f_cn, 10); // Write out invoice terms details left_margin = 40; top_margin = 620; writeText(cb, "Payment terms", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["payTerms"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, "Delivery terms", left_margin + 200, top_margin, f_cb, 10); writeText(cb, drHead["delTerms"].ToString(), left_margin + 200, top_margin - 12, f_cn, 10); writeText(cb, "Transport terms", left_margin + 350, top_margin, f_cb, 10); writeText(cb, drHead["delTransportTerms"].ToString(), left_margin + 350, top_margin - 12, f_cn, 10); // Move down left_margin = 40; top_margin = 590; writeText(cb, "Order reference", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["orderReference"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, "Customer marking", left_margin + 200, top_margin, f_cb, 10); writeText(cb, drHead["customerMarking"].ToString(), left_margin + 200, top_margin - 12, f_cn, 10); writeText(cb, "Salesman", left_margin + 350, top_margin, f_cb, 10); writeText(cb, drHead["salesman"].ToString(), left_margin + 350, top_margin - 12, f_cn, 10); // NOTE! You need to call the EndText() method before we can write graphics to the document! cb.EndText(); // Separate the header from the rows with a line // Draw a line by setting the line width and position cb.SetLineWidth(0f); cb.MoveTo(40, 570); cb.LineTo(560, 570); cb.Stroke(); // Don't forget to call the BeginText() method when done doing graphics! cb.BeginText(); // Before we write the lines, it's good to assign a "last position to write" // variable to validate against if we need to make a page break while outputting. // Change it to 510 to write to test a page break; the fourth line on a new page int lastwriteposition = 100; // Loop thru the rows in the rows table // Start by writing out the line headers top_margin = 550; left_margin = 40; // Line headers writeText(cb, "Item", left_margin, top_margin, f_cb, 10); writeText(cb, "Description", left_margin + 70, top_margin, f_cb, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Qty", left_margin + 415, top_margin, 0); writeText(cb, "Unit", left_margin + 420, top_margin, f_cb, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Price", left_margin + 495, top_margin, 0); writeText(cb, "Curr", left_margin + 500, top_margin, f_cb, 10); // First item line position starts here top_margin = 538; // Loop thru the table of items and set the linespacing to 12 points. // Note that we use the -= operator, the coordinates goes from the bottom of the page! foreach (DataRow drItem in invoice.GetInvoiceRows().Rows) { writeText(cb, drItem["itemId"].ToString(), left_margin, top_margin, f_cn, 10); writeText(cb, drItem["itemDescription"].ToString(), left_margin + 70, top_margin, f_cn, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drItem["invoicedQuantity"].ToString(), left_margin + 415, top_margin, 0); writeText(cb, drItem["unit"].ToString(), left_margin + 420, top_margin, f_cn, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drItem["price"].ToString(), left_margin + 495, top_margin, 0); writeText(cb, drItem["currency"].ToString(), left_margin + 500, top_margin, f_cn, 10); // This is the line spacing, if you change the font size, you might want to change this as well. top_margin -= 12; // Implement a page break function, checking if the write position has reached the lastwriteposition if (top_margin <= lastwriteposition) { // We need to end the writing before we change the page cb.EndText(); // Make the page break document.NewPage(); // Start the writing again cb.BeginText(); // Assign the new write location on page two! // Here you might want to implement a new header function for the new page top_margin = 780; } } // Okay, write out the totals table // Here you might want to do some page break scenarios, as well: // Example: // Calculate how many rows you are about to print and see if they fit before the lastwriteposition, // then decide how to do; write some on first page, then the rest on second page or perhaps all the // total lines after the page break. // We are not doing this here, we just write them out 80 points below the last writed item row top_margin -= 80; left_margin = 350; // First the headers writeText(cb, "Invoice line totals", left_margin, top_margin, f_cb, 10); writeText(cb, "Freight fee", left_margin, top_margin - 12, f_cb, 10); writeText(cb, "VAT amount", left_margin, top_margin - 24, f_cb, 10); writeText(cb, "Invoice grand total", left_margin, top_margin - 48, f_cb, 10); // Move right to write out the values left_margin = 540; // Write out the invoice currency and values in regular text cb.SetFontAndSize(f_cn, 10); string curr = drTotal["currency"].ToString(); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin - 12, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin - 24, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin - 48, 0); left_margin = 535; cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["invoicedAmount"].ToString(), left_margin, top_margin, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["freightCharge"].ToString(), left_margin, top_margin - 12, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["VAT"].ToString(), left_margin, top_margin - 24, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["totalAmount"].ToString(), left_margin, top_margin - 48, 0); // End the writing of text cb.EndText(); // Close the document, the writer and the filestream! document.Close(); writer.Close(); fs.Close(); lblMsg.Text = "Invoiced saved to the invoice folder. Good job!"; } } catch (Exception rror) { lblMsg.Text = rror.Message; } }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(p1Header); PdfPCell pdfCell3 = new PdfPCell(); String text = "Page " + writer.PageNumber + " of "; //Add paging to header { cb.BeginText(); cb.SetFontAndSize(bf, 12); cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); //Adds "12" in Page 1 of 12 cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45)); } //Add paging to footer { cb.BeginText(); cb.SetFontAndSize(bf, 12); cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30)); } //Row 2 PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal)); //Row 3 PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig)); PdfPCell pdfCell6 = new PdfPCell(); PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig)); //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM; pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.VerticalAlignment = Element.ALIGN_TOP; pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.Colspan = 3; pdfCell1.Border = 0; pdfCell2.Border = 0; pdfCell3.Border = 0; pdfCell4.Border = 0; pdfCell5.Border = 0; pdfCell6.Border = 0; pdfCell7.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.AddCell(pdfCell4); pdfTab.AddCell(pdfCell5); pdfTab.AddCell(pdfCell6); pdfTab.AddCell(pdfCell7); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //set pdfContent value //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(40, document.PageSize.Height - 100); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); cb.Stroke(); //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(); }
public Chap1015() { Console.WriteLine("Chapter 10 Example 15: Tiled Patterns"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap1015.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.DirectContent; BaseFont bf = BaseFont.CreateFont("Times-Roman", "winansi", false); // step 5: we create some PdfPatternPainter instances for drawing path, text, or placing image // Image instance to be placed in PdfPatternPainter canvas. Any nice one? Image img = Image.GetInstance("pngnow.png"); PdfPatternPainter p = cb.CreatePattern(60f, 60f, 60f, 60f); PdfPatternPainter p1 = cb.CreatePattern(60f, 60f, 60f, 60f); PdfPatternPainter p2 = cb.CreatePattern(img.ScaledWidth, img.ScaledHeight, img.ScaledWidth, img.ScaledHeight); // step 6: put your drawing instruction in the painter canvas // A star pattern taken from Adobe PDF Reference Book p.207 String star = "0.3 g\n15.000 27.000 m\n" + "7.947 5.292 l\n26.413 18.708 l\n" + "3.587 18.708 l\n22.053 5.292 l\nf\n" + "45.000 57.000 m\n37.947 35.292 l\n" + "56.413 48.708 l\n33.587 48.708 l\n" + "52.053 35.292 l\nf\n" + "0.7 g\n15.000 57.000 m\n" + "7.947 35.292 l\n26.413 48.708 l\n" + "3.587 48.708 l\n22.053 35.292 l\nf\n" + "45.000 27.000 m\n37.947 5.292 l\n" + "56.413 18.708 l\n33.587 18.708 l\n" + "52.053 5.292 l\nf"; p.SetLiteral(star); // A Pattern with some text drawing p1.SetGrayFill(0.3f); p1.SetFontAndSize(bf, 12); p1.BeginText(); p1.SetTextMatrix(1f, 0f, 0f, 1f, 0f, 0f); p1.ShowText("A B C D"); p1.EndText(); p1.MoveTo(0f, 0f); p1.LineTo(60f, 60f); p1.Stroke(); // A pattern with an image and position p2.AddImage(img, img.ScaledWidth, 0f, 0f, img.ScaledHeight, 0f, 0f); p2.SetPatternMatrix(1f, 0f, 0f, 1f, 60f, 60f); // See if we can apply the pattern color to chunk, phrase or paragraph PatternColor pat = new PatternColor(p); PatternColor pat1 = new PatternColor(p1); PatternColor pat2 = new PatternColor(p2); String text = "Text with pattern"; document.Add(new Paragraph(text, FontFactory.GetFont(FontFactory.HELVETICA, 60, Font.BOLD, new GrayColor(0.3f)))); document.Add(new Paragraph(text, FontFactory.GetFont(FontFactory.HELVETICA, 60, Font.BOLD, pat))); // draw a rectangle filled with star pattern cb.SetPatternFill(p); cb.SetGrayStroke(0.0f); cb.Rectangle(20, 20, 284, 120); cb.FillStroke(); // draw some characters filled with star. // Note: A gray, rgb, cmyk or spot color should be applied first // otherwise, you will not be able to see the character glyph // since the glyph path is filled by pattern cb.BeginText(); cb.SetFontAndSize(bf, 1); cb.SetTextMatrix(270f, 0f, 0f, 270f, 20f, 100f); cb.SetGrayFill(0.9f); cb.ShowText("ABC"); cb.SetPatternFill(p); cb.MoveTextWithLeading(0.0f, 0.0f); cb.ShowText("ABC"); cb.EndText(); cb.SetPatternFill(p); // draw a circle. Similar to rectangle cb.SetGrayStroke(0.0f); cb.Circle(150f, 400f, 150f); cb.FillStroke(); // New Page to draw text in the pattern painter's canvas document.NewPage(); document.Add(new Paragraph(text, FontFactory.GetFont(FontFactory.HELVETICA, 60, Font.BOLD, new GrayColor(0.3f)))); document.Add(new Paragraph(text, FontFactory.GetFont(FontFactory.HELVETICA, 60, Font.BOLD, pat1))); // draw a rectangle cb.SetPatternFill(p1); cb.SetGrayStroke(0.0f); cb.Rectangle(0, 0, 284, 120); cb.FillStroke(); // draw some characters cb.BeginText(); cb.SetFontAndSize(bf, 1); cb.SetTextMatrix(270f, 0f, 0f, 270f, 20f, 100f); cb.SetGrayFill(0.9f); cb.ShowText("ABC"); cb.SetPatternFill(p1); cb.MoveTextWithLeading(0.0f, 0.0f); cb.ShowText("ABC"); cb.EndText(); // draw a circle cb.SetPatternFill(p1); cb.SetGrayStroke(0.0f); cb.Circle(150f, 400f, 150f); cb.FillStroke(); // New page to place image in the pattern painter's canvas document.NewPage(); document.Add(new Paragraph(text, FontFactory.GetFont(FontFactory.HELVETICA, 60, Font.BOLD, new GrayColor(0.3f)))); document.Add(new Paragraph(text, FontFactory.GetFont(FontFactory.HELVETICA, 60, Font.BOLD, pat2))); // The original Image for comparison reason. // Note: The width and height is the same as bbox in pattern cb.AddImage(img, img.ScaledWidth, 0f, 0f, img.ScaledHeight, 350f, 400f); // draw a rectangle cb.SetPatternFill(p2); cb.SetGrayStroke(0.0f); cb.Rectangle(60, 60, 300, 120); cb.FillStroke(); // draw some characters. // Note: if the image fills up the pattern, there's no need to draw text twice // since colors in image will be clipped to character glyph path cb.BeginText(); cb.SetFontAndSize(bf, 1); cb.SetTextMatrix(270f, 0f, 0f, 270f, 60f, 120f); cb.SetPatternFill(p2); cb.ShowText("ABC"); cb.EndText(); // draw a circle cb.SetPatternFill(p2); cb.SetGrayStroke(0.0f); cb.Circle(150f, 400f, 150f); cb.FillStroke(); } catch (Exception e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); } // finally, we close the document document.Close(); }
private void ReportAsync() { CloseReport(); Document doc = new Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); using (var writer = PdfWriter.GetInstance(doc, new FileStream(path + DpfName, FileMode.Create, FileAccess.ReadWrite))) { int page = 1; BaseFont baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font fontbold = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.BOLD); doc.Open(); PdfContentByte cb = writer.DirectContent; #region 1 page doc.NewPage(); doc.Add(new Paragraph("", font)); HatsPrint(doc, cb, baseFont, ttf); cb.BeginText(); cb.ShowTextAligned(0, "Chart", 300, 680, 0); cb.EndText(); iTextSharp.text.Image HistoryChartIMG = Pcp.ImgScreenSchots(Dynamic, 0, 0); HistoryChartIMG.SetAbsolutePosition(25, 560); HistoryChartIMG.ScaleAbsolute(560, 95); cb.AddImage(HistoryChartIMG); Hat.DetailsPrint(cb, baseFont, "Return", 25, 545, 10); PDFTablesCreate tablecreator = new PDFTablesCreate(ActivesClasses, Convert.ToDecimal(Totalport)); PdfPTable table = new PdfPTable(3); table = Pcp.TablePrint(null, font, tablecreator.ReturnT, 90, 45, 95); table.WriteSelectedRows(0, -1, 25, 530, cb); Hat.DetailsPrint(cb, baseFont, "Allocation", 325, 545, 10); table = new PdfPTable(3); table = Pcp.TablePrint(null, font, tablecreator.AllocationT, 90, 50, 100); table.WriteSelectedRows(0, -1, 325, 530, cb); LowHatPrint(cb, baseFont, page); page++; #endregion #region 2 page - 3diagramm doc.NewPage(); HatsPrint(doc, cb, baseFont, ttf); Hat.DetailsPrint(cb, baseFont, "Current Portfel Chart", Convert.ToInt32(doc.PageSize.Width / 2 - 60), 680, 10); iTextSharp.text.Image CurrentPotrIMG = Pcp.ImgScreenSchots(CurrentP, 21, 21); CurrentPotrIMG.SetAbsolutePosition(0, 300); //1 картинка //CurrentPotrIMG.ScaleAbsolute(440, 190); //CurrentPotrIMG.ScaleAbsolute(200,200); cb.AddImage(CurrentPotrIMG); Hat.LinePrint(cb, 20, 523, 550, 523, 255, 255, 255, 26); // закрасить сверху Hat.LinePrint(cb, 20, 555, -120, 255, 255, 255, 255, 219); //закрасить слева //Легенда var colorsPortfels = Ext.CurPortBrush; int X = 465; int Y = 670; object KeyDiagramm = null; Diagramm dd = null; string isin = null; for (int i = 0; i < colorsPortfels.Count; i++) { System.Windows.Media.Brush diagrammitem = colorsPortfels.Values.ElementAt(i); KeyDiagramm = colorsPortfels.Keys.ElementAt(i); dd = (Diagramm)KeyDiagramm; isin = dd.Name; Pcp.RectangleTextPrint(cb, baseFont, isin, diagrammitem, X, Y); Y = Y - 15; } // LowHatPrint(cb, baseFont, page); page++; #endregion #region 3p Transactions doc.NewPage(); HatsPrint(doc, cb, baseFont, ttf); string date = DateTime.Now.ToString().Remove(11); Hat.DetailsPrint(cb, baseFont, "Cell Results * " + date, Convert.ToInt32(doc.PageSize.Width / 2 - 60), Convert.ToInt32(doc.PageSize.Height - 150), 10); table = Pcp.TablePrint(null, font, tablecreator.CellPolicy, 100, 100, 100, 130); table.WriteSelectedRows(0, -1, 100, 680, cb); Hat.DetailsPrint(cb, baseFont, "Holdings * " + date, Convert.ToInt32(doc.PageSize.Width / 2 - 60), Convert.ToInt32(doc.PageSize.Height - 270), 10); font.Size = 8; table = Pcp.TablePrint(new byte[] { 255, 255, 255 }, font, tablecreator.Holdings, 53, 35, 50, 55, 50, 70, 65, 70, 60, 50); table.WriteSelectedRows(0, -1, 25, 560, cb); LowHatPrint(cb, baseFont, page); table = new PdfPTable(5); var TBL = tablecreator.Transactions; var Count = Math.Abs(TBL.Rows.Count / 50) + 1; for (int i = 0; i < Count; i++) { doc.NewPage(); HatsPrint(doc, cb, baseFont, ttf); Hat.DetailsPrint(cb, baseFont, "Transactions * " + date, Convert.ToInt32(doc.PageSize.Width / 2 - 60), Convert.ToInt32(doc.PageSize.Height - 150), 10); table = Pcp.TablePrint(null, font, TBL, 103, 103, 103, 103, 103, 0, 0, 0, 0, 0, i, 50, Count - 1); table.WriteSelectedRows(0, -1, 25, 680, cb); page++; LowHatPrint(cb, baseFont, page); } page++; #endregion #region N page - end doc.NewPage(); HatsPrint(doc, cb, baseFont, ttf); cb.BeginText(); cb.ShowTextAligned(0, "Important Remarks : ", 30, 680, 0); ColumnText ct = new ColumnText(cb); Phrase myText = new Phrase(BigTextData.Remarks, font); ct.SetSimpleColumn(myText, 30, 665, 580, 317, 15, Element.ALIGN_LEFT); ct.Go(); cb.EndText(); LowHatPrint(cb, baseFont, page); #endregion doc.Close(); } if (open == true) { OpenReport(); } }
public string BuildInvoice(Order orderDetails, UserAccount userDetails, Invoice invoice) { BaseFont f_cb = BaseFont.CreateFont("c:\\windows\\fonts\\calibrib.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); BaseFont f_cn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); try { string currentDate = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString(); string projectPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString(); string invoiceName = "Invoice_" + orderDetails.Id.ToString() + "_" + currentDate + ".pdf"; using (System.IO.FileStream fs = new FileStream(projectPath + "\\Tmp\\" + invoiceName, FileMode.Create)) { Document document = new Document(PageSize.A4, 25, 25, 30, 1); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.AddAuthor("BookStore"); document.AddTitle("Customer Invoice - order id:" + orderDetails.Id.ToString()); document.Open(); PdfContentByte cb = writer.DirectContent; iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(projectPath + "\\Images\\logo.png"); png.ScaleAbsolute(200, 55); png.SetAbsolutePosition(40, 750); cb.AddImage(png); cb.BeginText(); writeText(cb, "BookStore Invoice", 350, 820, f_cb, 14); writeText(cb, "Invoice Id", 350, 800, f_cb, 10); writeText(cb, invoice.Id.ToString(), 420, 800, f_cn, 10); writeText(cb, "Order date", 350, 788, f_cb, 10); writeText(cb, orderDetails.OrderDate.ToString(), 420, 788, f_cn, 10); writeText(cb, "Order Id", 350, 776, f_cb, 10); writeText(cb, orderDetails.Id.ToString(), 420, 776, f_cn, 10); writeText(cb, "Customer Id", 350, 764, f_cb, 10); writeText(cb, orderDetails.User.Id.ToString(), 420, 764, f_cn, 10); int left_margin = 40; int top_margin = 720; writeText(cb, "Delivery address", left_margin, top_margin, f_cb, 10); writeText(cb, userDetails.PersonalData.FirstName + " " + userDetails.PersonalData.LastName, left_margin, top_margin - 12, f_cn, 10); writeText(cb, userDetails.PersonalData.Address.Street, left_margin, top_margin - 24, f_cn, 10); writeText(cb, userDetails.PersonalData.Address.PostalCode + " " + userDetails.PersonalData.Address.City, left_margin, top_margin - 36, f_cn, 10); writeText(cb, userDetails.PersonalData.Address.Country, left_margin, top_margin - 48, f_cn, 10); left_margin = 350; writeText(cb, "Invoice address", left_margin, top_margin, f_cb, 10); writeText(cb, ApplicationScope.CompanyName, left_margin, top_margin - 12, f_cn, 10); writeText(cb, ApplicationScope.CompanyStreet, left_margin, top_margin - 24, f_cn, 10); writeText(cb, ApplicationScope.CompanyPostalCode + " " + ApplicationScope.CompanyCity, left_margin, top_margin - 36, f_cn, 10); writeText(cb, ApplicationScope.CompanyCountry, left_margin, top_margin - 48, f_cn, 10); cb.EndText(); cb.SetLineWidth(0f); cb.MoveTo(40, 620); cb.LineTo(610, 620); cb.Stroke(); cb.BeginText(); int lastwriteposition = 100; top_margin = 600; left_margin = 40; writeText(cb, "Item Id", left_margin, top_margin, f_cb, 10); writeText(cb, "Description", left_margin + 70, top_margin, f_cb, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Qty", left_margin + 415, top_margin, 0); writeText(cb, "Unit", left_margin + 420, top_margin, f_cb, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Price", left_margin + 495, top_margin, 0); writeText(cb, "Curr", left_margin + 500, top_margin, f_cb, 10); top_margin = 588; Decimal totalInvoicedPrice = 0; foreach (OrderEntry entry in orderDetails.OrderEntries) { writeText(cb, entry.BookType.Id.ToString(), left_margin, top_margin, f_cn, 10); writeText(cb, entry.BookType.Authors + ", \"" + entry.BookType.Title + "\"", left_margin + 70, top_margin, f_cn, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, entry.Amount.ToString(), left_margin + 415, top_margin, 0); writeText(cb, ApplicationScope.InvoiceUnit, left_margin + 420, top_margin, f_cn, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, entry.Price.ToString(), left_margin + 495, top_margin, 0); writeText(cb, ApplicationScope.InvoiceCurrency, left_margin + 500, top_margin, f_cn, 10); totalInvoicedPrice = Decimal.Add(totalInvoicedPrice, Decimal.Multiply(entry.Price, (Decimal)entry.Amount)); top_margin -= 12; if (top_margin <= lastwriteposition) { cb.EndText(); document.NewPage(); cb.BeginText(); top_margin = 780; } } top_margin -= 80; left_margin = 350; writeText(cb, "Invoice line totals", left_margin, top_margin, f_cb, 10); writeText(cb, "VAT amount", left_margin, top_margin - 12, f_cb, 10); writeText(cb, "Invoice grand total", left_margin, top_margin - 36, f_cb, 10); left_margin = 540; cb.SetFontAndSize(f_cn, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ApplicationScope.InvoiceCurrency, left_margin, top_margin, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ApplicationScope.InvoiceCurrency, left_margin, top_margin - 12, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ApplicationScope.InvoiceCurrency, left_margin, top_margin - 36, 0); left_margin = 535; cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, totalInvoicedPrice.ToString(), left_margin, top_margin, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, invoice.VatPriceValue.ToString(), left_margin, top_margin - 12, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, invoice.TotalValue.ToString(), left_margin, top_margin - 36, 0); cb.EndText(); document.Close(); writer.Close(); fs.Close(); return(invoiceName); } } catch (Exception error) { System.Console.WriteLine(error.ToString()); return(null); } }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { string fullCode; if (codeType == CODE128_RAW) { int idx = code.IndexOf('\uffff'); if (idx < 0) fullCode = ""; else fullCode = code.Substring(idx + 1); } else if (codeType == CODE128_UCC) fullCode = GetHumanReadableUCCEAN(code); else fullCode = RemoveFNC1(code); float fontX = 0; if (font != null) { fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } string bCode; if (codeType == CODE128_RAW) { int idx = code.IndexOf('\uffff'); if (idx >= 0) bCode = code.Substring(0, idx); else bCode = code; } else { bCode = GetRawText(code, codeType == CODE128_UCC); } int len = bCode.Length; float fullWidth = (len + 2) * 11 * x + 2 * x; float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) barStartX = fontX - fullWidth; else textStartX = fullWidth - fontX; break; default: if (fontX > fullWidth) barStartX = (fontX - fullWidth) / 2; else textStartX = (fullWidth - fontX) / 2; break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) textStartY = barHeight - baseline; else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } byte[] bars = GetBarsCode128Raw(bCode); bool print = true; if (barColor != null) cb.SetColorFill(barColor); for (int k = 0; k < bars.Length; ++k) { float w = bars[k] * x; if (print) cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) cb.SetColorFill(textColor); cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return this.BarcodeSize; }
public void DownloadPDF2() { //Anda perfecto, //Hay q probar como hacerlo en memoria string oldFile = @"C:\Projects\Inquimex\Cotizador Online\ProductQuoteAppProject\ProductQuoteApp\bin\doc_origen.pdf"; string newFile = @"C:\Projects\Inquimex\Cotizador Online\ProductQuoteAppProject\ProductQuoteApp\bin\doc_destino.pdf"; // open the reader PdfReader reader = new PdfReader(oldFile); iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); // open the writer FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; // select the font properties BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetColorFill(BaseColor.RED); cb.SetFontAndSize(bf, 8); // write the text in the pdf content cb.BeginText(); string text = "Some random blablablabla..."; // put the alignment and coordinates here cb.ShowTextAligned(1, text, 520, 640, 0); cb.EndText(); cb.BeginText(); text = "Other random blabla..."; // put the alignment and coordinates here cb.ShowTextAligned(2, text, 100, 200, 0); cb.EndText(); //create the new page and add it to the pdf PdfImportedPage page = writer.GetImportedPage(reader, 1); cb.AddTemplate(page, 0, 0); //document.NewPage(); //Paragraph p = new Paragraph("aaaaaaaaaaaaaaaaaa", new iTextSharp.text.Font(bf)); //document.Add(p); //PdfImportedPage page2 = writer.GetImportedPage(reader, 2); //cb.AddTemplate(page2, 0, 0); //document.NewPage(); //Paragraph pwe = new Paragraph("aaaaaaaaaaaaaaaaaa", new iTextSharp.text.Font(bf)); //document.Add(p); //cb.EndLayer(); //PdfImportedPage page3 = writer.GetImportedPage(reader, 3); //cb.AddTemplate(page3, 0, 0); // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { string fullCode = code; float fontX = 0; string bCode = code; if (extended) bCode = GetCode39Ex(code); if (font != null) { if (generateChecksum && checksumText) fullCode += GetChecksum(bCode); if (startStopText) fullCode = "*" + fullCode + "*"; fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } if (generateChecksum) bCode += GetChecksum(bCode); int len = bCode.Length + 2; float fullWidth = len * (6 * x + 3 * x * n) + (len - 1) * x; float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) barStartX = fontX - fullWidth; else textStartX = fullWidth - fontX; break; default: if (fontX > fullWidth) barStartX = (fontX - fullWidth) / 2; else textStartX = (fullWidth - fontX) / 2; break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) textStartY = barHeight - baseline; else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } byte[] bars = GetBarsCode39(bCode); bool print = true; if (barColor != null) cb.SetColorFill(barColor); for (int k = 0; k < bars.Length; ++k) { float w = (bars[k] == 0 ? x : x * n); if (print) cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) cb.SetColorFill(textColor); cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return this.BarcodeSize; }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { Rectangle rect = this.BarcodeSize; float barStartX = 0; float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) textStartY = barHeight - baseline; else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } switch (codeType) { case EAN13: case UPCA: case UPCE: if (font != null) barStartX += font.GetWidthPoint(code[0], size); break; } byte[] bars = null; int[] guard = GUARD_EMPTY; switch (codeType) { case EAN13: bars = GetBarsEAN13(code); guard = GUARD_EAN13; break; case EAN8: bars = GetBarsEAN8(code); guard = GUARD_EAN8; break; case UPCA: bars = GetBarsEAN13("0" + code); guard = GUARD_UPCA; break; case UPCE: bars = GetBarsUPCE(code); guard = GUARD_UPCE; break; case SUPP2: bars = GetBarsSupplemental2(code); break; case SUPP5: bars = GetBarsSupplemental5(code); break; } float keepBarX = barStartX; bool print = true; float gd = 0; if (font != null && baseline > 0 && guardBars) { gd = baseline / 2; } if (barColor != null) cb.SetColorFill(barColor); for (int k = 0; k < bars.Length; ++k) { float w = bars[k] * x; if (print) { if (Array.BinarySearch(guard, k) >= 0) cb.Rectangle(barStartX, barStartY - gd, w - inkSpreading, barHeight + gd); else cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) cb.SetColorFill(textColor); cb.BeginText(); cb.SetFontAndSize(font, size); switch (codeType) { case EAN13: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 13; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case EAN8: for (int k = 0; k < 8; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = TEXTPOS_EAN8[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case UPCA: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 11; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (11 + 12 * 7), textStartY); cb.ShowText(code.Substring(11, 1)); break; case UPCE: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 7; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (9 + 6 * 7), textStartY); cb.ShowText(code.Substring(7, 1)); break; case SUPP2: case SUPP5: for (int k = 0; k < code.Length; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = (7.5f + (9 * k)) * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; } cb.EndText(); } return rect; }