public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; if (MeetingId.HasValue) { meeting = DbUtil.Db.Meetings.Single(mt => mt.MeetingId == MeetingId); Debug.Assert(meeting.MeetingDate != null, "meeting.MeetingDate != null"); NewMeetingInfo = new NewMeetingInfo { MeetingDate = meeting.MeetingDate.Value }; } var list1 = NewMeetingInfo.ByGroup ? ReportList2().ToList() : ReportList().ToList(); if (!list1.Any()) { Response.Write("no data found"); return; } Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "filename=foo.pdf"); doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64); var w = PdfWriter.GetInstance(doc, Response.OutputStream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; box = new PdfPCell(); box.Border = Rectangle.NO_BORDER; box.CellEvent = new CellEvent(); OrgInfo lasto = null; foreach (var o in list1) { lasto = o; var table = new PdfPTable(1); table.DefaultCell.Border = Rectangle.NO_BORDER; table.DefaultCell.Padding = 0; table.WidthPercentage = 100; if (meeting != null) { var q = from at in meeting.Attends where at.AttendanceFlag || AttendCommitmentCode.committed.Contains(at.Commitment ?? 0) orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new { at.MemberType.Code, Name2 = NewMeetingInfo.UseAltNames && at.Person.AltName.HasValue() ? at.Person.AltName : at.Person.Name2, at.PeopleId, at.Person.DOB }; if (q.Any()) { StartPageSet(o); } foreach (var a in q) { table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font)); } } else if (OrgSearchModel != null) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == o.OrgId join m in DbUtil.Db.OrgPeople(o.OrgId, o.Groups) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } else if (Filter?.GroupSelect == GroupSelectCode.Member) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == Filter.Id join m in DbUtil.Db.OrgFilterPeople(QueryId, null) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now where NewMeetingInfo.ByGroup == false || m.Groups.Contains((char)10 + o.Groups + (char)10) orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } else { var q = from m in DbUtil.Db.OrgFilterPeople(QueryId, null) orderby m.Name2 let p = DbUtil.Db.People.Single(pp => pp.PeopleId == m.PeopleId) let om = p.OrganizationMembers.SingleOrDefault(mm => mm.OrganizationId == Filter.Id) let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om == null ? "Guest" : om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } if ((OrgSearchModel != null && NewMeetingInfo.ByGroup == false) || (Filter != null && Filter.GroupSelect == GroupSelectCode.Member && meeting == null && !Filter.SgFilter.HasValue() && !Filter.NameFilter.HasValue() && !Filter.FilterIndividuals == true && !Filter.FilterTag == true && NewMeetingInfo.ByGroup == false)) { foreach (var m in RollsheetModel.FetchVisitors(o.OrgId, NewMeetingInfo.MeetingDate, true, NewMeetingInfo.UseAltNames)) { if (table.Rows.Count == 0) { StartPageSet(o); } table.AddCell(AddRow(m.VisitorType, m.Name2, m.PeopleId, m.BirthDate, "", boldfont)); } } if (!pageSetStarted) { continue; } var col = 0; var gutter = 20f; var colwidth = (doc.Right - doc.Left - gutter) / 2; var ct = new ColumnText(w.DirectContent); ct.AddElement(table); var status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, doc.Top); } else { ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, doc.Top); } status = ct.Go(); ++col; if (col > 1) { col = 0; doc.NewPage(); } } } if (!hasRows) { if (!pageSetStarted) { StartPageSet(lasto); } doc.Add(new Paragraph("no members as of this meeting date and time to show on rollsheet")); } doc.Close(); }
public MetaDo(Stream meta, PdfContentByte cb) { this.cb = cb; this.meta = new InputMeta(meta); }
public void SelectMetaObject(int index, PdfContentByte cb) { MetaObject obj = (MetaObject)MetaObjects[index]; if (obj == null) return; int style; switch (obj.Type) { case MetaObject.META_BRUSH: currentBrush = (MetaBrush)obj; style = currentBrush.Style; if (style == MetaBrush.BS_SOLID) { Color color = currentBrush.Color; cb.SetColorFill(color); } else if (style == MetaBrush.BS_HATCHED) { Color color = currentBackgroundColor; cb.SetColorFill(color); } break; case MetaObject.META_PEN: { currentPen = (MetaPen)obj; style = currentPen.Style; if (style != MetaPen.PS_NULL) { Color color = currentPen.Color; cb.SetColorStroke(color); cb.SetLineWidth(Math.Abs((float)currentPen.PenWidth * scalingX / extentWx)); switch (style) { case MetaPen.PS_DASH: cb.SetLineDash(18, 6, 0); break; case MetaPen.PS_DASHDOT: cb.SetLiteral("[9 6 3 6]0 d\n"); break; case MetaPen.PS_DASHDOTDOT: cb.SetLiteral("[9 3 3 3 3 3]0 d\n"); break; case MetaPen.PS_DOT: cb.SetLineDash(3, 0); break; default: cb.SetLineDash(0); break; } } break; } case MetaObject.META_FONT: { currentFont = (MetaFont)obj; break; } } }
/** Gets and initializes the 4 layers where the table is written to. The text or graphics are added to * one of the 4 <CODE>PdfContentByte</CODE> returned with the following order:<p> * <ul> * <li><CODE>PdfPtable.BASECANVAS</CODE> - the original <CODE>PdfContentByte</CODE>. Anything placed here * will be under the table. * <li><CODE>PdfPtable.BACKGROUNDCANVAS</CODE> - the layer where the background goes to. * <li><CODE>PdfPtable.LINECANVAS</CODE> - the layer where the lines go to. * <li><CODE>PdfPtable.TEXTCANVAS</CODE> - the layer where the text go to. Anything placed here * will be over the table. * </ul><p> * The layers are placed in sequence on top of each other. * @param canvas the <CODE>PdfContentByte</CODE> where the rows will * be written to * @return an array of 4 <CODE>PdfContentByte</CODE> * @see #writeSelectedRows(int, int, float, float, PdfContentByte[]) */ public static PdfContentByte[] BeginWritingRows(PdfContentByte canvas) { return new PdfContentByte[]{ canvas, canvas.Duplicate, canvas.Duplicate, canvas.Duplicate, }; }
/** * Creates a <CODE>ColumnText</CODE>. * @param text the place where the text will be written to. Can * be a template. */ public ColumnText(PdfContentByte canvas) { this.canvas = canvas; }
/** 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) { if (barColor != null) cb.SetColorFill(barColor); byte[] bars = GetBarsPostnet(code); byte flip = 1; if (codeType == PLANET) { flip = 0; bars[0] = 0; bars[bars.Length - 1] = 0; } float startX = 0; for (int k = 0; k < bars.Length; ++k) { cb.Rectangle(startX, 0, x - inkSpreading, bars[k] == flip ? barHeight : size); startX += n; } cb.Fill(); return this.BarcodeSize; }
/** * Constructs a <CODE>PdfWriter</CODE>. * <P> * Remark: a PdfWriter can only be constructed by calling the method * <CODE>getInstance(Document document, Stream os)</CODE>. * * @param document The <CODE>PdfDocument</CODE> that has to be written * @param os The <CODE>Stream</CODE> the writer has to write to. */ protected PdfWriter(PdfDocument document, Stream os) : base(document, os) { root = new PdfPages(this); pdf = document; directContent = new PdfContentByte(this); directContentUnder = new PdfContentByte(this); }
private void CreatePdfBox(PdfContentByte content, Configuration.PrintTemplateContentRow row) { CreatePdfBox(content, row, true); }
public void Write(HttpResponse response, bool inline) { response.Clear(); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", (inline ? "inline" : "attachment") + "; filename=Map.pdf"); // create the PDF document Configuration config = AppContext.GetConfiguration(); Configuration.PrintTemplateRow printTemplate = config.PrintTemplate.First(o => o.TemplateID == _templateId); float pageWidth = Convert.ToSingle(printTemplate.PageWidth * PointsPerInch); float pageHeight = Convert.ToSingle(printTemplate.PageHeight * PointsPerInch); Rectangle pageSize = new Rectangle(pageWidth, pageHeight); pageSize.BackgroundColor = new Color(System.Drawing.Color.White); Document document = new Document(pageSize); PdfWriter writer = PdfWriter.GetInstance(document, response.OutputStream); document.Open(); PdfContentByte content = writer.DirectContent; // get the extent of the main map and fit it to the proportions of // the map box on the page double mapScale = 0; Configuration.PrintTemplateContentRow mapElement = printTemplate.GetPrintTemplateContentRows().FirstOrDefault(o => o.ContentType == "map"); if (mapElement != null) { if (_preserveMode == PreserveMode.Extent) { _appState.Extent.Reaspect(mapElement.Width, mapElement.Height); } else { IPoint c = new Point(_appState.Extent.Centre); double dx; double dy; if (_preserveMode == PreserveMode.Scale) { double ratio = _appState.Extent.Width * 96 / _originalWidth; dx = mapElement.Width * ratio * 0.5; dy = mapElement.Height * ratio * 0.5; } else { dx = _appState.Extent.Width * 0.5; dy = dx * mapElement.Height / mapElement.Width; } _appState.Extent = new Envelope(new Coordinate(c.Coordinate.X - dx, c.Coordinate.Y - dy), new Coordinate(c.Coordinate.X + dx, c.Coordinate.Y + dy)); } double conversion = AppSettings.MapUnits == "feet" ? 1 : Constants.FeetPerMeter; mapScale = _appState.Extent.Width * conversion / mapElement.Width; _pixelSize = _appState.Extent.Width / (mapElement.Width * PixelsPerInch); } int inputIndex = 0; // get the page template elements and draw each one to the page foreach (Configuration.PrintTemplateContentRow element in printTemplate.GetPrintTemplateContentRows()) { switch (element.ContentType) { case "box": CreatePdfBox(content, element); break; case "date": CreatePdfText(content, element, DateTime.Now.ToString("MMMM d, yyyy")); break; case "image": CreatePdfImage(content, element); break; case "legend": CreatePdfLegend(content, element); break; case "map": CreatePdfMap(content, element); break; case "overviewmap": CreatePdfOverviewMap(content, element); break; case "scale": if (mapScale > 0) { CreatePdfText(content, element, "1\" = " + mapScale.ToString("0") + " ft"); } break; case "scalefeet": if (mapScale > 0) { CreatePdfText(content, element, mapScale.ToString("0") + " ft"); } break; case "tabdata": CreatePdfTabData(content, element); break; case "text": if (!element.IsTextNull()) { CreatePdfText(content, element, element.Text); } else if (!element.IsFileNameNull()) { string fileName = HttpContext.Current.Server.MapPath("Text/Print") + "\\" + element.FileName; if (File.Exists(fileName)) { string text = File.ReadAllText(fileName); CreatePdfText(content, element, text); } } break; case "input": if (inputIndex < _input.Count) { CreatePdfText(content, element, _input[inputIndex]); ++inputIndex; } break; } } document.Close(); response.End(); }
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); }
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(); } }
/** * Write out the columns. After writing, use * {@link #isOverflow()} to see if all text was written. * @param canvas PdfContentByte to write with * @param document document to write to (only used to get page limit info) * @param documentY starting y position to begin writing at * @return the current height (y position) after writing the columns * @throws DocumentException on error */ public float Write(PdfContentByte canvas, PdfDocument document, float documentY) { this.document = document; columnText.Canvas = canvas; if (columnDefs.Count == 0) { throw new DocumentException(MessageLocalization.GetComposedMessage("multicolumntext.has.no.columns")); } overflow = false; float currentHeight = 0; bool done = false; while (!done) { if (top == AUTOMATIC) { top = document.GetVerticalPosition(true); } else if (nextY == AUTOMATIC) { nextY = document.GetVerticalPosition(true); // RS - 07/07/2005 - - Get current doc writing position for top of columns on new page. } ColumnDef currentDef = columnDefs[CurrentColumn]; columnText.YLine = top; float[] left = currentDef.ResolvePositions(Rectangle.LEFT_BORDER); float[] right = currentDef.ResolvePositions(Rectangle.RIGHT_BORDER); if (document.IsMarginMirroring() && document.PageNumber % 2 == 0) { float delta = document.RightMargin - document.Left; left = (float[])left.Clone(); right = (float[])right.Clone(); for (int i = 0; i < left.Length; i += 2) { left[i] -= delta; } for (int i = 0; i < right.Length; i += 2) { right[i] -= delta; } } currentHeight = Math.Max(currentHeight, GetHeight(left, right)); if (currentDef.IsSimple()) { columnText.SetSimpleColumn(left[2], left[3], right[0], right[1]); } else { columnText.SetColumns(left, right); } int result = columnText.Go(); if ((result & ColumnText.NO_MORE_TEXT) != 0) { done = true; top = columnText.YLine; } else if (ShiftCurrentColumn()) { top = nextY; } else // check if we are done because of height { totalHeight += currentHeight; if ((desiredHeight != AUTOMATIC) && (totalHeight >= desiredHeight)) { overflow = true; break; } else // need to start new page and reset the columns { documentY = nextY; NewPage(); currentHeight = 0; } } } if (desiredHeight == AUTOMATIC && columnDefs.Count == 1) { currentHeight = documentY - columnText.YLine; } return(currentHeight); }
public override void OnOpenDocument(PdfWriter writer, Document document) { // create the fonts that are to be used // first the hightlight or Bold font fontTxtBold = FontFactory.GetFont(_boldFont.fontFamily, _boldFont.fontSize, _boldFont.foreColor); if (_boldFont.isBold) { fontTxtBold.SetStyle(Font.BOLD); } if (_boldFont.isItalic) { fontTxtBold.SetStyle(Font.ITALIC); } if (_boldFont.isUnderlined) { fontTxtBold.SetStyle(Font.UNDERLINE); } // next the normal font fontTxtRegular = FontFactory.GetFont(_normalFont.fontFamily, _normalFont.fontSize, _normalFont.foreColor); if (_normalFont.isBold) { fontTxtRegular.SetStyle(Font.BOLD); } if (_normalFont.isItalic) { fontTxtRegular.SetStyle(Font.ITALIC); } if (_normalFont.isUnderlined) { fontTxtRegular.SetStyle(Font.UNDERLINE); } // now build the header and footer templates try { float pageHeight = document.PageSize.Height; float pageWidth = document.PageSize.Width; _headerWidth = (int)pageWidth - ((int)_rightMargin + (int)_leftMargin); _footerWidth = _headerWidth; if (hasHeader) { // i basically dummy build the headers so i can trial fit them and see how much space they take. float[] widths = new float[1] { 90f }; PdfPTable hdrTable = new PdfPTable(1); hdrTable.TotalWidth = document.PageSize.Width - (_leftMargin + _rightMargin); hdrTable.WidthPercentage = 95; hdrTable.SetWidths(widths); hdrTable.LockedWidth = true; _headerHeight = 0; for (int hdrIdx = 0; hdrIdx < (_headerLines.Length < 2 ? 2 : _headerLines.Length); hdrIdx++) { Paragraph hdrPara = new Paragraph(5, hdrIdx > _headerLines.Length - 1 ? string.Empty : _headerLines[hdrIdx], (hdrIdx > 0 ? fontTxtRegular : fontTxtBold)); PdfPCell hdrCell = new PdfPCell(hdrPara); hdrCell.HorizontalAlignment = Element.ALIGN_LEFT; hdrCell.Border = 0; hdrTable.AddCell(hdrCell); _headerHeight = _headerHeight + (int)hdrTable.GetRowHeight(hdrIdx); } // iTextSharp underestimates the size of each line so fudge it a little // this gives me 3 extra lines to play with on the spacing _headerHeight = _headerHeight + (_fontPointSize * 3); } if (hasFooter) { _footerHeight = (_fontPointSize * 2); } document.SetMargins(_leftMargin, _rightMargin, (_topMargin + _headerHeight), _footerHeight); cb = writer.DirectContent; if (hasHeader) { headerTemplate = cb.CreateTemplate(_headerWidth, _headerHeight); } if (hasFooter) { footerTemplate = cb.CreateTemplate(_footerWidth, _footerHeight); } } catch (DocumentException de) { } catch (System.IO.IOException ioe) { } }
public void TestSplitLateAndSplitRow1() { String filename = "testSplitLateAndSplitRow1.pdf"; Document doc = new Document(PageSize.LETTER, 72f, 72f, 72f, 72f); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outFolder + filename, FileMode.Create)); doc.Open(); PdfContentByte canvas = writer.DirectContent; ColumnText ct = new ColumnText(canvas); StringBuilder text = new StringBuilder(); for (int i = 0; i < 21; ++i) { text.Append(i).Append("\n"); } // Add a table with a single row and column that doesn't fit on one page PdfPTable t = new PdfPTable(1); t.SplitLate = true; t.SplitRows = true; t.WidthPercentage = 100f; ct.AddElement( new Paragraph( "Pushing table down\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\n")); PdfPCell c = new PdfPCell(); c.HorizontalAlignment = Element.ALIGN_LEFT; c.VerticalAlignment = Element.ALIGN_TOP; c.Border = Rectangle.NO_BORDER; c.BorderWidth = 0; c.Padding = 0; c.AddElement(new Paragraph(text.ToString())); t.AddCell(c); ct.AddElement(t); int status = 0; while (ColumnText.HasMoreText(status)) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Right, doc.Top); status = ct.Go(); if (ColumnText.HasMoreText(status)) { doc.NewPage(); } } doc.Close(); String errorMessage = new CompareTool().CompareByContent(outFolder + filename, cmpFolder + filename, outFolder, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
internal void WriteLine(PdfLine line, PdfContentByte text, PdfContentByte graphics) { PdfFont currentFont = null; foreach(PdfChunk chunk in line) { if (chunk.Font.CompareTo(currentFont) != 0) { currentFont = chunk.Font; text.SetFontAndSize(currentFont.Font, currentFont.Size); } Color color = chunk.Color; if (color != null) text.SetColorFill(color); text.ShowText(chunk.ToString()); if (color != null) text.ResetRGBColorFill(); } }
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(); }
/** * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[]) */ public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { float sp_left = spacing_left; if (float.IsNaN(sp_left)) sp_left = 0f; float sp_right = spacing_right; if (float.IsNaN(sp_right)) sp_right = 0f; float sp_top = spacing_top; if (float.IsNaN(sp_top)) sp_top = 0f; float sp_bottom = spacing_bottom; if (float.IsNaN(sp_bottom)) sp_bottom = 0f; Rectangle rect = new Rectangle(position.GetLeft(sp_left), position.GetBottom(sp_bottom), position.GetRight(sp_right), position.GetTop(sp_top)); rect.CloneNonPositionParameters(this); canvases[PdfPTable.BACKGROUNDCANVAS].Rectangle(rect); rect.BackgroundColor = null; canvases[PdfPTable.LINECANVAS].Rectangle(rect); }
/** 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 abstract Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor);
/** * @see com.lowagie.text.pdf.draw.DrawInterface#draw(com.lowagie.text.pdf.PdfContentByte, float, float, float, float, float) */ public override void Draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) { canvas.SaveState(); DrawLine(canvas, llx, urx, y); canvas.RestoreState(); }
/** Creates an <CODE>Image</CODE> with the barcode. * @param cb the <CODE>PdfContentByte</CODE> to create the <CODE>Image</CODE>. It * serves no other use * @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 <CODE>Image</CODE> * @see #placeBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) */ virtual public Image CreateImageWithBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) { return(Image.GetInstance(CreateTemplateWithBarcode(cb, barColor, textColor))); }
/** * Writes the selected rows to the document. * * @param rowStart the first row to be written, zero index * @param rowEnd the last row to be written + 1. If it is -1 all the * rows to the end are written * @param xPos the x write coodinate * @param yPos the y write coodinate * @param canvas the <CODE>PdfContentByte</CODE> where the rows will * be written to * @return the y coordinate position of the bottom of the last row */ public float WriteSelectedRows(int rowStart, int rowEnd, float xPos, float yPos, PdfContentByte canvas) { return WriteSelectedRows(0, -1, rowStart, rowEnd, xPos, yPos, canvas); }
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); }
/** * @see com.lowagie.text.pdf.PdfPTableEvent#tableLayout(com.lowagie.text.pdf.PdfPTable, float[][], float[], int, int, com.lowagie.text.pdf.PdfContentByte[]) */ public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) { float[] width = widths[0]; Rectangle rect = new Rectangle(width[0], heights[heights.Length - 1], width[width.Length - 1], heights[0]); rect.CloneNonPositionParameters(this); int bd = rect.Border; rect.Border = Rectangle.NO_BORDER; canvases[PdfPTable.BACKGROUNDCANVAS].Rectangle(rect); rect.Border = bd; rect.BackgroundColor = null; canvases[PdfPTable.LINECANVAS].Rectangle(rect); }
virtual public int Layout(PdfContentByte canvas, bool useAscender, bool simulate, float llx, float lly, float urx, float ury) { float leftX = Math.Min(llx, urx); float maxY = Math.Max(lly, ury); float minY = Math.Min(lly, ury); float rightX = Math.Max(llx, urx); yLine = maxY; bool contentCutByFixedHeight = false; if (width != null && width > 0) { if (width < rightX - leftX) { rightX = leftX + (float)width; } else if (width > rightX - leftX) { return(ColumnText.NO_MORE_COLUMN); } } else if (percentageWidth != null) { contentWidth = (rightX - leftX) * (float)percentageWidth; rightX = leftX + contentWidth; } if (height != null && height > 0) { if (height < maxY - minY) { contentCutByFixedHeight = true; minY = maxY - (float)height; } else if (height > maxY - minY) { return(ColumnText.NO_MORE_COLUMN); } } else if (percentageHeight != null) { if (percentageHeight < 1.0) { contentCutByFixedHeight = true; } contentHeight = (maxY - minY) * (float)percentageHeight; minY = maxY - contentHeight; } if (!simulate && position == PdfDiv.PositionType.RELATIVE) { float?translationX = null; if (left != null) { translationX = left; } else if (right != null) { translationX = -right; } else { translationX = 0f; } float?translationY = null; if (top != null) { translationY = -top; } else if (bottom != null) { translationY = bottom; } else { translationY = 0f; } canvas.SaveState(); canvas.Transform(new AffineTransform(1f, 0, 0, 1f, translationX.Value, translationY.Value)); } if (!simulate) { if (backgroundColor != null && getActualWidth() > 0 && getActualHeight() > 0) { float backgroundWidth = getActualWidth(); float backgroundHeight = getActualHeight(); if (width != null) { backgroundWidth = width > 0 ? (float)width : 0; } if (height != null) { backgroundHeight = height > 0 ? (float)height : 0; } if (backgroundWidth > 0 && backgroundHeight > 0) { Rectangle background = new Rectangle(leftX, maxY - backgroundHeight, leftX + backgroundWidth, maxY); background.BackgroundColor = backgroundColor; PdfArtifact artifact = new PdfArtifact(); canvas.OpenMCBlock(artifact); canvas.Rectangle(background); canvas.CloseMCBlock(artifact); } } } if (percentageWidth == null) { contentWidth = 0; } if (percentageHeight == null) { contentHeight = 0; } minY += paddingBottom; leftX += paddingLeft; rightX -= paddingRight; yLine -= paddingTop; int status = ColumnText.NO_MORE_TEXT; if (content.Count > 0) { if (floatLayout == null) { List <IElement> floatingElements = new List <IElement>(content); floatLayout = new FloatLayout(floatingElements, useAscender); } floatLayout.SetSimpleColumn(leftX, minY, rightX, yLine); status = floatLayout.Layout(canvas, simulate); yLine = floatLayout.YLine; if (percentageWidth == null && contentWidth < floatLayout.FilledWidth) { contentWidth = floatLayout.FilledWidth; } } if (!simulate && position == PdfDiv.PositionType.RELATIVE) { canvas.RestoreState(); } yLine -= paddingBottom; if (percentageHeight == null) { contentHeight = maxY - yLine; } if (percentageWidth == null) { contentWidth += paddingLeft + paddingRight; } return(contentCutByFixedHeight ? ColumnText.NO_MORE_TEXT : status); }
/** Shows a line of text. Only the first line is written. * @param canvas where the text is to be written to * @param alignment the alignment * @param phrase the <CODE>Phrase</CODE> with the text * @param x the x reference position * @param y the y reference position * @param rotation the rotation to be applied in degrees counterclockwise */ public static void ShowTextAligned(PdfContentByte canvas, int alignment, Phrase phrase, float x, float y, float rotation) { ShowTextAligned(canvas, alignment, phrase, x, y, rotation, PdfWriter.RUN_DIRECTION_NO_BIDI, 0); }
//metodo para crear el pdf al vuelo del saef public byte[] FormarPDF(string HTML, string fileName, string Cabecera, string Pie, string Folio, bool nuevo) { PdfConverter pdfConverter = new PdfConverter(); byte[] bPdf = null; byte[] bResp = null; try { pdfConverter.LicenseKey = "f1ROX0dfTk9OTl9KUU9fTE5RTk1RRkZGRg=="; //Header pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfHeaderOptions.HeaderHeight = 190; pdfConverter.PdfHeaderOptions.HtmlToPdfArea = new HtmlToPdfArea(Cabecera, null); pdfConverter.PdfHeaderOptions.DrawHeaderLine = false; if (nuevo == false) { //pie pdfConverter.PdfFooterOptions.FooterHeight = 100; pdfConverter.PdfFooterOptions.HtmlToPdfArea = new HtmlToPdfArea(Pie, null); pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfFooterOptions.DrawFooterLine = false; } //poner el numero de paginacion pdfConverter.PdfFooterOptions.TextArea = new TextArea(5, -5, "Página &p; de &P; ", new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 8, System.Drawing.GraphicsUnit.Point)); pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true; pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; //margenes pdfConverter.PdfDocumentOptions.LeftMargin = 40; pdfConverter.PdfDocumentOptions.RightMargin = 40; pdfConverter.PdfDocumentOptions.StretchToFit = true; bPdf = pdfConverter.GetPdfBytesFromHtmlString(HTML); if (nuevo) { //metodo para poner el logo de fondo try { string rutaFondo = "https://sistemas.indaabin.gob.mx/ImagenesComunes/nuevoescudo.png"; MemoryStream stream = new MemoryStream(); iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(bPdf); //crear el objeto pdfstamper que se utiliza para agregar contenido adicional al archivo pdf fuente iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, stream); //iterar a través de todas las páginas del archivo fuente pdf for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) { PdfContentByte overContent = pdfStamper.GetOverContent(pageIndex); iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(rutaFondo); overContent.SaveState(); overContent.SetGState(new PdfGState { FillOpacity = 0.3f, StrokeOpacity = 0.3f//0.3 }); overContent.AddImage(jpeg, 560f, 0f, 0f, 820f, 0f, 0f); overContent.RestoreState(); } //cerrar stamper y filestream de salida pdfStamper.Close(); stream.Close(); pdfReader.Close(); bResp = stream.ToArray(); pdfStamper = null; pdfReader = null; stream = null; } catch (Exception ex) { } } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Acessibilidad" + " " + fileName + " " + Folio + ".pdf"); if (nuevo) { HttpContext.Current.Response.BinaryWrite(bResp); } else { HttpContext.Current.Response.BinaryWrite(bPdf); } HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (Exception ex) { } return(bPdf); //return bPdf; }
public void RestoreState(int index, PdfContentByte cb) { int pops; if (index < 0) pops = Math.Min(-index, savedStates.Count); else pops = Math.Max(savedStates.Count - index, 0); if (pops == 0) return; MetaState state = null; while (pops-- != 0) { cb.RestoreState(); state = (MetaState)savedStates.Pop(); } metaState = state; }
public virtual void DeviceNSpotBasedGradient() { // step 1 Document document = new Document(PageSize.A3); // step 2 String dest_file = DEST_FOLDER + "/device_n_gradient_base.pdf"; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(dest_file, FileMode.Create)); // step 3 document.Open(); // step 4 PdfContentByte canvas = writer.DirectContent; PdfSpotColor psc_gray = new PdfSpotColor("iTextGray", new GrayColor(0f)); PdfSpotColor psc_cmyk_yell = new PdfSpotColor("iTextYellow", new CMYKColor(0f, 0f, 1f, 0f)); PdfSpotColor psc_cmyk_magen = new PdfSpotColor("iTextMagenta", new CMYKColor(0f, 1f, 0f, 0f)); PdfSpotColor psc_rgb_blue = new PdfSpotColor("iTextBlue", new BaseColor(0, 0, 255)); PdfDeviceNColor pdfDeviceNNChannelColor = new PdfDeviceNColor(new PdfSpotColor[] { psc_cmyk_yell, psc_cmyk_magen, psc_rgb_blue }); PdfDeviceNColor pdfDeviceNNChannelColor2 = new PdfDeviceNColor(new PdfSpotColor[] { psc_cmyk_magen, psc_cmyk_yell, psc_rgb_blue }); ColorRectangle(canvas, new SpotColor(new PdfSpotColor("iTextGray", new GrayColor(0f)), 0.8f), 36, 824, 36, 36); ColorRectangle(canvas, new SpotColor(new PdfSpotColor("iTextYellow", new CMYKColor(0f, 0f, 1f, 0f)), 0.8f), 90, 824, 36, 36); ColorRectangle(canvas, new SpotColor(new PdfSpotColor("iTextMagenta", new CMYKColor(0f, 1f, 0f, 0f)), 0.4f), 144, 824, 36, 36); ColorRectangle(canvas, new SpotColor(new PdfSpotColor("iTextBlue", new BaseColor(0, 0, 255)), 0.7f), 198, 824, 36, 36); ColorRectangle(canvas, new DeviceNColor(new PdfDeviceNColor(new PdfSpotColor[] { psc_cmyk_yell, psc_cmyk_magen, psc_rgb_blue }), new float[] { 0, 0.0f, 1 }), 36, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 0.1f, 0.1f, 1 }), 90, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 0.2f, 0.2f, 1 }), 144, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 0.3f, 0.3f, 1 }), 198, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 0.4f, 0.4f, 1 }), 252, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(new PdfDeviceNColor(new PdfSpotColor[] { psc_cmyk_yell, psc_cmyk_magen, psc_rgb_blue, psc_gray }), new float[] { 0.5f, 0.5f, 1, 0.5f }), 306, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor2, new float[] { 0.6f, 0.1f, 1 }), 360, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 0.7f, 0.7f, 1 }), 416, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 0.8f, 0.8f, 1 }), 470, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(new PdfDeviceNColor(new PdfSpotColor[] { psc_cmyk_yell, psc_cmyk_magen, psc_rgb_blue }), new float[] { 0.9f, 0.9f, 1 }), 524, 770, 36, 36); ColorRectangle(canvas, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 1, 1, 1 }), 578, 770, 36, 36); PdfDeviceNColor pdfDeviceNColor = new PdfDeviceNColor(new PdfSpotColor[] { psc_cmyk_yell, psc_cmyk_magen, psc_rgb_blue }); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0, 0, 1 })); canvas.Rectangle(36, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.1f, 0.1f, 1 })); canvas.Rectangle(90, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.2f, 0.2f, 1 })); canvas.Rectangle(144, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.3f, 0.3f, 1 })); canvas.Rectangle(198, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.4f, 0.4f, 1 })); canvas.Rectangle(252, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.5f, 0.5f, 1 })); canvas.Rectangle(306, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.6f, 0.1f, 1 })); canvas.Rectangle(360, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.7f, 0.7f, 1 })); canvas.Rectangle(416, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.8f, 0.8f, 1 })); canvas.Rectangle(470, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 0.9f, 0.9f, 1 })); canvas.Rectangle(524, 716, 36, 36); canvas.FillStroke(); canvas.SetColorFill(new DeviceNColor(pdfDeviceNColor, new float[] { 1, 1, 1 })); canvas.Rectangle(578, 716, 36, 36); canvas.FillStroke(); canvas.SaveState(); canvas.Rectangle(418, 412, -329, 189); canvas.Clip(); canvas.NewPath(); canvas.SaveState(); canvas.ConcatCTM(329f, 0f, 0f, -329f, 89f, 506.5f); canvas.PaintShading(PdfShading.SimpleAxial(writer, 0, 0, 1, 0, new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 1, 1, 0 }), new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 0, 0, 1 }))); canvas.RestoreState(); canvas.RestoreState(); canvas.SetColorStroke(new DeviceNColor(pdfDeviceNNChannelColor, new float[] { 1, 1, 1 })); canvas.Rectangle(418, 412, -329, 189); canvas.Stroke(); // step 5 document.Close(); CompareTool compareTool = new CompareTool(dest_file, TEST_RESOURCES_PATH + "cmp_device_n_gradient_base.pdf"); String error = compareTool.Compare(DEST_FOLDER, "diff_"); if (error != null) { Assert.Fail(error); } }
public PdfFormField AddMap(string name, string value, string url, PdfContentByte appearance, float llx, float lly, float urx, float ury) { PdfAction action = PdfAction.CreateSubmitForm(url, null, PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES); PdfFormField button = new PdfFormField(writer, llx, lly, urx, ury, action); SetButtonParams(button, PdfFormField.FF_PUSHBUTTON, name, null); PdfAppearance pa = PdfAppearance.CreateAppearance(writer, urx - llx, ury - lly); pa.Add(appearance); button.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, pa); AddFormField(button); return button; }
public override void OnOpenDocument(PdfWriter writer, Document document) { cb = writer.DirectContent; template = cb.CreateTemplate(50, 50); }
/** Creates new VerticalText * @param text the place where the text will be written to. Can * be a template. */ public VerticalText(PdfContentByte text) { this.text = text; }
public PdfDictionary GetEncryptionDictionary() { PdfDictionary dic = new PdfDictionary(); if (publicKeyHandler.GetRecipientsSize() > 0) { PdfArray recipients = null; dic.Put(PdfName.FILTER, PdfName.PUBSEC); dic.Put(PdfName.R, new PdfNumber(revision)); recipients = publicKeyHandler.GetEncodedRecipients(); if (revision == STANDARD_ENCRYPTION_40) { dic.Put(PdfName.V, new PdfNumber(1)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.Put(PdfName.RECIPIENTS, recipients); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.Put(PdfName.V, new PdfNumber(2)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.Put(PdfName.RECIPIENTS, recipients); } else { dic.Put(PdfName.R, new PdfNumber(AES_128)); dic.Put(PdfName.V, new PdfNumber(4)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.RECIPIENTS, recipients); if (!encryptMetadata) { stdcf.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } if (revision == AES_128) { stdcf.Put(PdfName.CFM, PdfName.AESV2); } else { stdcf.Put(PdfName.CFM, PdfName.V2); } PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.DEFAULTCRYPTFILTER, stdcf); dic.Put(PdfName.CF, cf); if (embeddedFilesOnly) { dic.Put(PdfName.EFF, PdfName.DEFAULTCRYPTFILTER); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { dic.Put(PdfName.STRF, PdfName.DEFAULTCRYPTFILTER); dic.Put(PdfName.STMF, PdfName.DEFAULTCRYPTFILTER); } } SHA1 sh = new SHA1CryptoServiceProvider(); byte[] encodedRecipient = null; byte[] seed = publicKeyHandler.GetSeed(); sh.TransformBlock(seed, 0, seed.Length, seed, 0); for (int i = 0; i < publicKeyHandler.GetRecipientsSize(); i++) { encodedRecipient = publicKeyHandler.GetEncodedRecipient(i); sh.TransformBlock(encodedRecipient, 0, encodedRecipient.Length, encodedRecipient, 0); } if (!encryptMetadata) { sh.TransformBlock(metadataPad, 0, metadataPad.Length, metadataPad, 0); } sh.TransformFinalBlock(seed, 0, 0); byte[] mdResult = sh.Hash; SetupByEncryptionKey(mdResult, keyLength); } else { dic.Put(PdfName.FILTER, PdfName.STANDARD); dic.Put(PdfName.O, new PdfLiteral(PdfContentByte.EscapeString(ownerKey))); dic.Put(PdfName.U, new PdfLiteral(PdfContentByte.EscapeString(userKey))); dic.Put(PdfName.P, new PdfNumber(permissions)); dic.Put(PdfName.R, new PdfNumber(revision)); if (revision == STANDARD_ENCRYPTION_40) { dic.Put(PdfName.V, new PdfNumber(1)); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.Put(PdfName.V, new PdfNumber(2)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); } else { if (!encryptMetadata) { dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } dic.Put(PdfName.R, new PdfNumber(AES_128)); dic.Put(PdfName.V, new PdfNumber(4)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.LENGTH, new PdfNumber(16)); if (embeddedFilesOnly) { stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.Put(PdfName.EFF, PdfName.STDCF); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.Put(PdfName.STRF, PdfName.STDCF); dic.Put(PdfName.STMF, PdfName.STDCF); } if (revision == AES_128) { stdcf.Put(PdfName.CFM, PdfName.AESV2); } else { stdcf.Put(PdfName.CFM, PdfName.V2); } PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.STDCF, stdcf); dic.Put(PdfName.CF, cf); } } return(dic); }
/** 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) { if (supp.Font != null) supp.BarHeight = ean.BarHeight + supp.Baseline - supp.Font.GetFontDescriptor(BaseFont.CAPHEIGHT, supp.Size); else supp.BarHeight = ean.BarHeight; Rectangle eanR = ean.BarcodeSize; cb.SaveState(); ean.PlaceBarcode(cb, barColor, textColor); cb.RestoreState(); cb.SaveState(); cb.ConcatCTM(1, 0, 0, 1, eanR.Width + n, eanR.Height - ean.BarHeight); supp.PlaceBarcode(cb, barColor, textColor); cb.RestoreState(); 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, 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); }
public static PdfAnnotation CreateFreeText(PdfWriter writer, Rectangle rect, string contents, PdfContentByte defaultAppearance) { PdfAnnotation annot = new PdfAnnotation(writer, rect); annot.Put(PdfName.SUBTYPE, PdfName.FREETEXT); annot.Put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE)); annot.DefaultAppearanceString = defaultAppearance; return annot; }
public Concat(String[] args) { if (args.Length < 3) { Console.Error.WriteLine("This tools needs at least 3 parameters:\njava Concat destfile file1 file2 [file3 ...]"); } else { try { int f = 1; // we create a reader for a certain document PdfReader reader = new PdfReader(args[f]); // we retrieve the total number of pages int n = reader.NumberOfPages; Console.WriteLine("There are " + n + " pages in the original file."); // step 1: creation of a document-object Document document = new Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(args[0], FileMode.Create)); // step 3: we open the document document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; int rotation; // step 4: we add content while (f < args.Length) { int i = 0; while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(i)); document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } Console.WriteLine("Processed page " + i); } f++; if (f < args.Length) { reader = new PdfReader(args[f]); // we retrieve the total number of pages n = reader.NumberOfPages; Console.WriteLine("There are " + n + " pages in the original file."); } } // step 5: we close the document document.Close(); } catch (Exception e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); } } }
/** 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; }
/** * Writes parts of text which are visible into a content stream. */ private void WriteTextChunks(IDictionary <int, float> structuredTJoperands, IList <PdfCleanUpContentChunk> chunks, PdfContentByte canvas, float characterSpacing, float wordSpacing, float fontSize, float horizontalScaling) { canvas.SetCharacterSpacing(0); canvas.SetWordSpacing(0); canvas.InternalBuffer.Append((byte)'['); float convertedCharacterSpacing = -characterSpacing * 1000f / fontSize; float convertedWordSpacing = -wordSpacing * 1000f / fontSize; float shift = structuredTJoperands != null ? structuredTJoperands[0] : 0; PdfCleanUpContentChunk.Text prevChunk = null; foreach (PdfCleanUpContentChunk chunk in chunks) { PdfCleanUpContentChunk.Text textChunk = (PdfCleanUpContentChunk.Text)chunk; if (prevChunk != null && prevChunk.NumOfStrTextBelongsTo != textChunk.NumOfStrTextBelongsTo && structuredTJoperands != null) { shift += structuredTJoperands[prevChunk.NumOfStrTextBelongsTo]; } if (textChunk.Visible) { if (Util.compare(shift, 0.0f) != 0 && Util.compare(shift, -0.0f) != 0) { canvas.InternalBuffer.Append(shift).Append(' '); } textChunk.GetText().ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(' '); shift = convertedCharacterSpacing + (IsSpace(textChunk) ? convertedWordSpacing : 0); } else { shift += GetUnscaledTextChunkWidth(textChunk, characterSpacing, wordSpacing, fontSize, horizontalScaling); } prevChunk = textChunk; } if (Util.compare(shift, 0) != 0 && Util.compare(shift, -0.0f) != 0) { canvas.InternalBuffer.Append(shift); } canvas.InternalBuffer.Append(TJ); if (Util.compare(characterSpacing, 0) != 0 && Util.compare(characterSpacing, -0.0f) != 0) { new PdfNumber(characterSpacing).ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(Tc); } if (Util.compare(wordSpacing, 0) != 0 && Util.compare(wordSpacing, -0.0f) != 0) { new PdfNumber(wordSpacing).ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(Tw); } }
/** * Draws a horizontal line. * @param canvas the canvas to draw on * @param leftX the left x coordinate * @param rightX the right x coordindate * @param y the y coordinate */ virtual public void DrawLine(PdfContentByte canvas, float leftX, float rightX, float y) { float w; if (Percentage < 0) w = -Percentage; else w = (rightX - leftX) * Percentage / 100.0f; float s; switch (Alignment) { case Element.ALIGN_LEFT: s = 0; break; case Element.ALIGN_RIGHT: s = rightX - leftX - w; break; default: s = (rightX - leftX - w) / 2; break; } canvas.SetLineWidth(LineWidth); if (LineColor != null) canvas.SetColorStroke(LineColor); canvas.MoveTo(s + leftX, y + offset); canvas.LineTo(s + w + leftX, y + offset); canvas.Stroke(); }
public virtual void Invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral oper, List <PdfObject> operands) { String operatorStr = oper.ToString(); PdfContentByte canvas = cleanUpStrategy.Context.Canvas; PRStream xFormStream = null; bool disableOutput = pathConstructionOperators.Contains(operatorStr) || pathPaintingOperators.Contains(operatorStr) || clippingPathOperators.Contains(operatorStr); // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0. // BE AWARE: zero-length strings are ignored!!! IDictionary <int, float> structuredTJoperands = null; if ("Do" == operatorStr) { if (operands.Count == 2 && operands[0].IsName()) { PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT); if (xObjResources != null) { PdfStream xObj = xObjResources.GetAsStream((PdfName)operands[0]); if (xObj is PRStream && xObj.GetAsName(PdfName.SUBTYPE) != null && xObj.GetAsName(PdfName.SUBTYPE).CompareTo(PdfName.FORM) == 0) { xFormStream = (PRStream)xObj; cleanUpStrategy.RegisterNewContext(xObj.GetAsDict(PdfName.RESOURCES), null); } } } } originalContentOperator.Invoke(pdfContentStreamProcessor, oper, operands); IList <PdfCleanUpContentChunk> chunks = cleanUpStrategy.Chunks; if (xFormStream != null) { xFormStream.SetData(cleanUpStrategy.Context.Canvas.ToPdf(cleanUpStrategy.Context.Canvas.PdfWriter)); cleanUpStrategy.PopContext(); canvas = cleanUpStrategy.Context.Canvas; } if ("Do" == operatorStr) { if (chunks.Count > 0 && chunks[0] is PdfCleanUpContentChunk.Image) { PdfCleanUpContentChunk.Image chunk = (PdfCleanUpContentChunk.Image)chunks[0]; if (chunk.Visible) { PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT); PRStream imageStream = (PRStream)xObjResources.GetAsStream((PdfName)operands[0]); UpdateImageStream(imageStream, chunk.NewImageData); } else { disableOutput = true; } } } else if (lineStyleOperators.Contains(operatorStr)) { disableOutput = true; } else if (textShowingOperators.Contains(operatorStr) && !AllChunksAreVisible(cleanUpStrategy.Chunks)) { disableOutput = true; if ("'" == operatorStr) { canvas.InternalBuffer.Append(TStar); } else if ("\"" == operatorStr) { operands[0].ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(Tw); operands[1].ToPdf(canvas.PdfWriter, canvas.InternalBuffer); canvas.InternalBuffer.Append(TcTStar); } else if ("TJ" == operatorStr) { structuredTJoperands = StructureTJarray((PdfArray)operands[0]); } GraphicsState gs = pdfContentStreamProcessor.Gs(); WriteTextChunks(structuredTJoperands, chunks, canvas, gs.CharacterSpacing, gs.WordSpacing, gs.FontSize, gs.HorizontalScaling); } else if (pathPaintingOperators.Contains(operatorStr)) { WritePath(operatorStr, canvas); } else if (strokeColorOperators.Contains(operatorStr)) { // Replace current color with the new one. cleanUpStrategy.Context.PopStrokeColor(); cleanUpStrategy.Context.PushStrokeColor(operands); } else if ("q" == operatorStr) { cleanUpStrategy.Context.PushStrokeColor(cleanUpStrategy.Context.PeekStrokeColor()); } else if ("Q" == operatorStr) { cleanUpStrategy.Context.PopStrokeColor(); } if (!disableOutput) { WriteOperands(canvas, operands); } cleanUpStrategy.ClearChunks(); }
/** Writes the selected rows and columns to the document. * This method does not clip the columns; this is only important * if there are columns with colspan at boundaries. * <P> * <CODE>canvases</CODE> is obtained from <CODE>beginWritingRows()</CODE>. * <P> * The table event is only fired for complete rows. * @param colStart the first column to be written, zero index * @param colEnd the last column to be written + 1. If it is -1 all the * columns to the end are written * @param rowStart the first row to be written, zero index * @param rowEnd the last row to be written + 1. If it is -1 all the * rows to the end are written * @param xPos the x write coodinate * @param yPos the y write coodinate * @param canvases an array of 4 <CODE>PdfContentByte</CODE> obtained from * <CODE>beginWrittingRows()</CODE> * @return the y coordinate position of the bottom of the last row * @see #beginWritingRows(com.lowagie.text.pdf.PdfContentByte) */ public float WriteSelectedRows(int colStart, int colEnd, int rowStart, int rowEnd, float xPos, float yPos, PdfContentByte[] canvases) { if (totalWidth <= 0) throw new ArgumentException("The table width must be greater than zero."); int totalRows = rows.Count; if (rowStart < 0) rowStart = 0; if (rowEnd < 0) rowEnd = totalRows; else rowEnd = Math.Min(rowEnd, totalRows); if (rowStart >= rowEnd) return yPos; int totalCols = NumberOfColumns; if (colStart < 0) colStart = 0; else colStart = Math.Min(colStart, totalCols); if (colEnd < 0) colEnd = totalCols; else colEnd = Math.Min(colEnd, totalCols); float yPosStart = yPos; for (int k = rowStart; k < rowEnd; ++k) { PdfPRow row = (PdfPRow)rows[k]; if (row != null) { row.WriteCells(colStart, colEnd, xPos, yPos, canvases); yPos -= row.MaxHeights; } } if (tableEvent != null && colStart == 0 && colEnd == totalCols) { float[] heights = new float[rowEnd - rowStart + 1]; heights[0] = yPosStart; for (int k = rowStart; k < rowEnd; ++k) { PdfPRow row = (PdfPRow)rows[k]; float hr = 0; if (row != null) hr = row.MaxHeights; heights[k - rowStart + 1] = heights[k - rowStart] - hr; } tableEvent.TableLayout(this, GetEventWidths(xPos, rowStart, rowEnd, headersInEvent), heights, headersInEvent ? headerRows : 0, rowStart, canvases); } return yPos; }
/** 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); }
/** * Writes the selected rows to the document. * This method clips the columns; this is only important * if there are columns with colspan at boundaries. * <P> * The table event is only fired for complete rows. * * @param colStart the first column to be written, zero index * @param colEnd the last column to be written + 1. If it is -1 all the * @param rowStart the first row to be written, zero index * @param rowEnd the last row to be written + 1. If it is -1 all the * rows to the end are written * @param xPos the x write coodinate * @param yPos the y write coodinate * @param canvas the <CODE>PdfContentByte</CODE> where the rows will * be written to * @return the y coordinate position of the bottom of the last row */ public float WriteSelectedRows(int colStart, int colEnd, int rowStart, int rowEnd, float xPos, float yPos, PdfContentByte canvas) { int totalCols = NumberOfColumns; if (colStart < 0) colStart = 0; else colStart = Math.Min(colStart, totalCols); if (colEnd < 0) colEnd = totalCols; else colEnd = Math.Min(colEnd, totalCols); bool clip = (colStart != 0 || colEnd != totalCols); if (clip) { float w = 0; for (int k = colStart; k < colEnd; ++k) w += absoluteWidths[k]; canvas.SaveState(); float lx = (colStart == 0) ? 10000 : 0; float rx = (colEnd == totalCols) ? 10000 : 0; canvas.Rectangle(xPos - lx, -10000, w + lx + rx, PdfPRow.RIGHT_LIMIT); canvas.Clip(); canvas.NewPath(); } PdfContentByte[] canvases = BeginWritingRows(canvas); float y = WriteSelectedRows(colStart, colEnd, rowStart, rowEnd, xPos, yPos, canvases); EndWritingRows(canvases); if (clip) canvas.RestoreState(); return y; }
// constructor /** * Constructs a <CODE>PdfContents</CODE>-object, containing text and general graphics. * * @param under the direct content that is under all others * @param content the graphics in a page * @param text the text in a page * @param secondContent the direct content that is over all others * @throws BadPdfFormatException on error */ internal PdfContents(PdfContentByte under, PdfContentByte content, PdfContentByte text, PdfContentByte secondContent, Rectangle page) : base() { Stream ostr = null; streamBytes = new MemoryStream(); if (Document.Compress) { compressed = true; int compresLevel; if (text != null) { compresLevel = text.PdfWriter.CompressionLevel; } else { compresLevel = content.PdfWriter.CompressionLevel; } ostr = new ZDeflaterOutputStream(streamBytes, compresLevel); } else { ostr = streamBytes; } int rotation = page.Rotation; byte[] tmp; switch (rotation) { case 90: ostr.Write(ROTATE90, 0, ROTATE90.Length); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Top)); ostr.Write(tmp, 0, tmp.Length); ostr.WriteByte((byte)' '); ostr.WriteByte((byte)'0'); ostr.Write(ROTATEFINAL, 0, ROTATEFINAL.Length); break; case 180: ostr.Write(ROTATE180, 0, ROTATE180.Length); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Right)); ostr.Write(tmp, 0, tmp.Length); ostr.WriteByte((byte)' '); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Top)); ostr.Write(tmp, 0, tmp.Length); ostr.Write(ROTATEFINAL, 0, ROTATEFINAL.Length); break; case 270: ostr.Write(ROTATE270, 0, ROTATE270.Length); ostr.WriteByte((byte)'0'); ostr.WriteByte((byte)' '); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Right)); ostr.Write(tmp, 0, tmp.Length); ostr.Write(ROTATEFINAL, 0, ROTATEFINAL.Length); break; } if (under.Size > 0) { ostr.Write(SAVESTATE, 0, SAVESTATE.Length); under.InternalBuffer.WriteTo(ostr); ostr.Write(RESTORESTATE, 0, RESTORESTATE.Length); } if (content.Size > 0) { ostr.Write(SAVESTATE, 0, SAVESTATE.Length); content.InternalBuffer.WriteTo(ostr); ostr.Write(RESTORESTATE, 0, RESTORESTATE.Length); } if (text != null) { ostr.Write(SAVESTATE, 0, SAVESTATE.Length); text.InternalBuffer.WriteTo(ostr); ostr.Write(RESTORESTATE, 0, RESTORESTATE.Length); } if (secondContent.Size > 0) { secondContent.InternalBuffer.WriteTo(ostr); } if (ostr is ZDeflaterOutputStream) { ((ZDeflaterOutputStream)ostr).Finish(); } Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length)); if (compressed) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } }
/** Finishes writing the table. * @param canvases the array returned by <CODE>beginWritingRows()</CODE> */ public static void EndWritingRows(PdfContentByte[] canvases) { PdfContentByte canvas = canvases[BASECANVAS]; canvas.SaveState(); canvas.Add(canvases[BACKGROUNDCANVAS]); canvas.RestoreState(); canvas.SaveState(); canvas.SetLineCap(2); canvas.ResetRGBColorStroke(); canvas.Add(canvases[LINECANVAS]); canvas.RestoreState(); canvas.Add(canvases[TEXTCANVAS]); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "filename=foo.pdf"); dt = Util.Now; doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64); var w = PdfWriter.GetInstance(doc, Response.OutputStream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; t = new PdfPTable(1); t.WidthPercentage = 100; t.DefaultCell.Padding = 0; t.HeaderRows = 1; t.AddCell(StartPageSet()); t.DefaultCell.Border = PdfPCell.TOP_BORDER; t.DefaultCell.BorderColor = BaseColor.BLACK; t.DefaultCell.BorderColorTop = BaseColor.BLACK; t.DefaultCell.BorderWidthTop = 2.0f; var q = DbUtil.Db.PeopleQuery(qid); var q2 = from p in q let person = p group p by p.FamilyId into g let hhname = g.First().Family.HeadOfHousehold.Name2 orderby hhname select new { members = from m in g.First().Family.People where !m.DeceasedDate.HasValue select new { order = m.PositionInFamilyId * 1000 + (m.PositionInFamilyId == 10 ? m.GenderId : 1000 - (m.Age ?? 0)), // order = g.Any(p => p.PeopleId == m.PeopleId) ? 1 : // m.PositionInFamilyId, person = m } }; foreach (var f in q2) { var ft = new PdfPTable(HeaderWids); ft.DefaultCell.SetLeading(2.0f, 1f); ft.DefaultCell.Border = PdfPCell.NO_BORDER; ft.DefaultCell.Padding = 5; int fn = 1; var color = BaseColor.BLACK; foreach (var p in f.members.OrderBy(m => m.order)) { if (color == BaseColor.WHITE) { color = new GrayColor(240); } else { color = BaseColor.WHITE; } Debug.WriteLine("{0:##}: {1}".Fmt(p.order, p.person.Name)); AddRow(ft, p.person, fn, color); fn++; } t.AddCell(ft); } if (t.Rows.Count > 1) { doc.Add(t); } else { doc.Add(new Phrase("no data")); } pageEvents.EndPageSet(); doc.Close(); }
protected internal void SetSimpleVars(ColumnText org) { maxY = org.maxY; minY = org.minY; alignment = org.alignment; leftWall = null; if (org.leftWall != null) leftWall = new ArrayList(org.leftWall); rightWall = null; if (org.rightWall != null) rightWall = new ArrayList(org.rightWall); yLine = org.yLine; currentLeading = org.currentLeading; fixedLeading = org.fixedLeading; multipliedLeading = org.multipliedLeading; canvas = org.canvas; canvases = org.canvases; lineStatus = org.lineStatus; indent = org.indent; followingIndent = org.followingIndent; rightIndent = org.rightIndent; extraParagraphSpace = org.extraParagraphSpace; rectangularWidth = org.rectangularWidth; rectangularMode = org.rectangularMode; spaceCharRatio = org.spaceCharRatio; lastWasNewline = org.lastWasNewline; linesWritten = org.linesWritten; arabicOptions = org.arabicOptions; runDirection = org.runDirection; descender = org.descender; composite = org.composite; splittedRow = org.splittedRow; if (org.composite) { compositeElements = new ArrayList(org.compositeElements); if (splittedRow) { PdfPTable table = (PdfPTable)compositeElements[0]; compositeElements[0] = new PdfPTable(table); } if (org.compositeColumn != null) compositeColumn = Duplicate(org.compositeColumn); } listIdx = org.listIdx; firstLineY = org.firstLineY; leftX = org.leftX; rightX = org.rightX; firstLineYDone = org.firstLineYDone; waitPhrase = org.waitPhrase; useAscender = org.useAscender; filledWidth = org.filledWidth; adjustFirstLine = org.adjustFirstLine; }
public MemoryStream GeneratePdfTemplate(GarmentPackingListViewModel viewModel) { //int maxSizesCount = viewModel.Items == null || viewModel.Items.Count < 1 ? 0 : viewModel.Items.Max(i => i.Details == null || i.Details.Count < 1 ? 0 : i.Details.Max(d => d.Sizes == null || d.Sizes.Count < 1 ? 0 : d.Sizes.GroupBy(g => g.Size.Id).Count())); var newItems = new List <GarmentPackingListItemViewModel>(); var newItems2 = new List <GarmentPackingListItemViewModel>(); var newDetails = new List <GarmentPackingListDetailViewModel>(); foreach (var item in viewModel.Items.OrderBy(a => a.RONo)) { foreach (var detail in item.Details) { newDetails.Add(detail); } } newDetails = newDetails.OrderBy(a => a.Carton1).ToList(); foreach (var d in newDetails) { if (newItems.Count == 0) { var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId); i.Details = new List <GarmentPackingListDetailViewModel>(); i.Details.Add(d); newItems.Add(i); } else { if (newItems.Last().Id == d.PackingListItemId) { newItems.Last().Details.Add(d); } else { var y = viewModel.Items.OrderBy(o => o.RONo).Select(a => new GarmentPackingListItemViewModel { Id = a.Id, RONo = a.RONo, Article = a.Article, BuyerAgent = a.BuyerAgent, ComodityDescription = a.ComodityDescription, OrderNo = a.OrderNo, AVG_GW = a.AVG_GW, AVG_NW = a.AVG_NW, Uom = a.Uom }) .Single(a => a.Id == d.PackingListItemId); y.Details = new List <GarmentPackingListDetailViewModel>(); y.Details.Add(d); newItems.Add(y); } } } foreach (var item in newItems) { if (newItems2.Count == 0) { newItems2.Add(item); } else { if (newItems2.Last().RONo == item.RONo && newItems2.Last().OrderNo == item.OrderNo) { foreach (var d in item.Details.OrderBy(a => a.Carton1)) { newItems2.Last().Details.Add(d); } } else { newItems2.Add(item); } } } var sizesCount = false; foreach (var item in newItems2) { var sizesMax = new Dictionary <int, string>(); foreach (var detail in item.Details) { foreach (var size in detail.Sizes) { sizesMax[size.Size.Id] = size.Size.Size; } } if (sizesMax.Count > 11) { sizesCount = true; } } int SIZES_COUNT = sizesCount ? 20 : 11; Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font body_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Document document = new Document(sizesCount ? PageSize.A4.Rotate() : PageSize.A4, 20, 20, 70, 30); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PageEvent = new GarmentPackingListDraftPdfByCartonTemplatePageEvent(_identityProvider, viewModel); document.Open(); PdfContentByte cb = writer.DirectContent; PdfPCell cellBorderBottomRight = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; PdfPCell cellBorderBottom = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; var cartons = new List <GarmentPackingListDetailViewModel>(); double grandTotal = 0; var arraySubTotal = new Dictionary <String, double>(); List <string> cartonNumbers = new List <string>(); document.Add(new Paragraph("SHIPPING METHOD : " + viewModel.ShipmentMode + "\n", normal_font)); foreach (var item in newItems2) { #region Item PdfPTable tableItem = new PdfPTable(6); tableItem.SetWidths(new float[] { 2f, 0.2f, 2.8f, 2f, 0.2f, 2.8f }); PdfPCell cellItemContent = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellItemContent.Phrase = new Phrase("RO No", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(":", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(item.RONo, normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase("ARTICLE", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(":", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(item.Article, normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase("BUYER", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(":", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(viewModel.BuyerAgent.Name, normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase("", normal_font); cellItemContent.Phrase = new Phrase("DESCRIPTION OF GOODS", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(":", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(item.ComodityDescription, normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase("", normal_font); tableItem.AddCell(cellItemContent); tableItem.AddCell(cellItemContent); tableItem.AddCell(cellItemContent); new PdfPCell(tableItem); tableItem.ExtendLastRow = false; document.Add(tableItem); #endregion var sizes = new Dictionary <int, string>(); foreach (var detail in item.Details) { foreach (var size in detail.Sizes) { sizes[size.Size.Id] = size.Size.Size; } } PdfPTable tableDetail = new PdfPTable(SIZES_COUNT + 11); var width = new List <float> { 2f, 3.5f, 4f, 4f }; for (int i = 0; i < SIZES_COUNT; i++) { width.Add(1f); } width.AddRange(new List <float> { 1.5f, 1f, 1.5f, 2f, 1.5f, 1.5f, 1.5f }); tableDetail.SetWidths(width.ToArray()); PdfPCell cellDetailLine = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = 19, Padding = 0.5f, Phrase = new Phrase("") }; tableDetail.AddCell(cellDetailLine); tableDetail.AddCell(cellDetailLine); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("CARTON NO.", normal_font, 0.75f)); cellBorderBottomRight.Rowspan = 2; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("COLOUR", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("STYLE", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("ORDER NO.", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("S I Z E", normal_font, 0.75f)); cellBorderBottomRight.Colspan = SIZES_COUNT; cellBorderBottomRight.Rowspan = 1; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("CTNS", normal_font, 0.75f)); cellBorderBottomRight.Colspan = 1; cellBorderBottomRight.Rowspan = 2; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("@", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("QTY", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SATUAN", normal_font, 0.75f)); cellBorderBottomRight.Colspan = 1; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("GW/\nCTN", normal_font, 0.75f)); cellBorderBottomRight.Rowspan = 2; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NW/\nCTN", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NNW/\nCTN", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Rowspan = 1; for (int i = 0; i < SIZES_COUNT; i++) { var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(size.Key == 0 ? "" : size.Value, normal_font, 0.5f)); cellBorderBottomRight.Rowspan = 1; tableDetail.AddCell(cellBorderBottomRight); } var subCartons = new List <GarmentPackingListDetailViewModel>(); var subGrossWeight = new List <GarmentPackingListDetailViewModel>(); var subNetWeight = new List <GarmentPackingListDetailViewModel>(); var subNetNetWeight = new List <GarmentPackingListDetailViewModel>(); double subTotal = 0; var sizeSumQty = new Dictionary <int, double>(); foreach (var detail in item.Details) { var ctnsQty = detail.CartonQuantity; var grossWeight = detail.GrossWeight; var netWeight = detail.NetWeight; var netNetWeight = detail.NetNetWeight; if (cartonNumbers.Contains($"{detail.Index}-{detail.Carton1}- {detail.Carton2}")) { ctnsQty = 0; grossWeight = 0; netWeight = 0; netNetWeight = 0; } else { cartonNumbers.Add($"{detail.Index}-{detail.Carton1}- {detail.Carton2}"); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk($"{detail.Carton1}- {detail.Carton2}", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Colour, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Style, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.OrderNo, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); for (int i = 0; i < SIZES_COUNT; i++) { var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i); double quantity = 0; if (size.Key != 0) { quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity); } if (sizeSumQty.ContainsKey(size.Key)) { sizeSumQty[size.Key] += quantity * detail.CartonQuantity; } else { sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(ctnsQty.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.QuantityPCS.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS); subTotal += totalQuantity; cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(totalQuantity.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.Uom.Unit, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.GrossWeight), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetWeight), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetNetWeight), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); if (cartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0) { cartons.Add(new GarmentPackingListDetailViewModel { Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty }); } if (subCartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0) { subCartons.Add(new GarmentPackingListDetailViewModel { Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty }); subGrossWeight.Add(new GarmentPackingListDetailViewModel { Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, GrossWeight = grossWeight }); subNetWeight.Add(new GarmentPackingListDetailViewModel { Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetWeight = netWeight }); subNetNetWeight.Add(new GarmentPackingListDetailViewModel { Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetNetWeight = netNetWeight }); } } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SUMMARY", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); for (int i = 0; i < SIZES_COUNT; i++) { var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i); double quantity = 0; if (size.Key != 0) { quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.5f)); tableDetail.AddCell(cellBorderBottomRight); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); grandTotal += subTotal; if (!arraySubTotal.ContainsKey(item.Uom.Unit)) { arraySubTotal.Add(item.Uom.Unit, subTotal); } else { arraySubTotal[item.Uom.Unit] += subTotal; } tableDetail.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = SIZES_COUNT + 7, Padding = 5, Phrase = new Phrase("SUB TOTAL ....................................................................................................................................................................... ", normal_font) }); cellBorderBottom.Phrase = new Phrase(subTotal.ToString() + " " + item.Uom.Unit, normal_font); cellBorderBottom.Colspan = 2; tableDetail.AddCell(cellBorderBottom); cellBorderBottom.Phrase = new Phrase("", normal_font); cellBorderBottom.Colspan = 3; tableDetail.AddCell(cellBorderBottom); cellBorderBottom.Colspan = 1; var subCtns = subCartons.Sum(c => c.CartonQuantity); var subGw = subGrossWeight.Sum(c => c.CartonQuantity * c.GrossWeight); var subNw = subNetWeight.Sum(c => c.CartonQuantity * c.NetWeight); var subNnw = subNetNetWeight.Sum(c => c.CartonQuantity * c.NetNetWeight); tableDetail.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = SIZES_COUNT + 11, Phrase = new Phrase($" - Sub Ctns = {subCtns} - Sub G.W. = {String.Format("{0:0.00}", subGw)} Kgs - Sub N.W. = {String.Format("{0:0.00}", subNw)} Kgs - Sub N.N.W. = {String.Format("{0:0.00}", subNnw)} Kgs", normal_font) }); new PdfPCell(tableDetail); tableDetail.ExtendLastRow = false; //tableDetail.KeepTogether = true; tableDetail.WidthPercentage = 95f; //tableDetail.HeaderRows = 3; document.Add(tableDetail); } #region GrandTotal PdfPTable tableGrandTotal = new PdfPTable(2); tableGrandTotal.SetWidths(new float[] { 18f + SIZES_COUNT * 1f, 5f }); PdfPCell cellHeaderLine = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = 2, Padding = 0.5f, Phrase = new Phrase("") }; tableGrandTotal.AddCell(cellHeaderLine); tableGrandTotal.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Padding = 5, Phrase = new Phrase("GRAND TOTAL .......................................................................................................................................................................", normal_font) }); var grandTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray()); tableGrandTotal.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Padding = 5, HorizontalAlignment = Element.ALIGN_CENTER, Phrase = new Phrase(grandTotalResult, normal_font) }); tableGrandTotal.AddCell(cellHeaderLine); var totalCtns = cartons.Sum(c => c.CartonQuantity); var comodities = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct(); tableGrandTotal.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Colspan = 2, Padding = 5, Phrase = new Phrase($"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", comodities)}]", normal_font) }); new PdfPCell(tableGrandTotal); tableGrandTotal.ExtendLastRow = false; tableGrandTotal.WidthPercentage = 95f; tableGrandTotal.SpacingAfter = 5f; document.Add(tableGrandTotal); #endregion #region Mark PdfPTable tableMark = new PdfPTable(2); tableMark.SetWidths(new float[] { 1f, 1f }); PdfPCell cellShippingMark = new PdfPCell() { Border = Rectangle.NO_BORDER }; Chunk chunkShippingMark = new Chunk("SHIPPING MARKS", normal_font); chunkShippingMark.SetUnderline(0.5f, -1); Phrase phraseShippingMark = new Phrase(); phraseShippingMark.Add(chunkShippingMark); phraseShippingMark.Add(new Chunk(" :", normal_font)); cellShippingMark.AddElement(phraseShippingMark); cellShippingMark.AddElement(new Paragraph(viewModel.ShippingMark, normal_font)); tableMark.AddCell(cellShippingMark); PdfPCell cellSideMark = new PdfPCell() { Border = Rectangle.NO_BORDER }; Chunk chunkSideMark = new Chunk("SIDE MARKS", normal_font); chunkSideMark.SetUnderline(0.5f, -1); Phrase phraseSideMark = new Phrase(); phraseSideMark.Add(chunkSideMark); phraseSideMark.Add(new Chunk(" :", normal_font)); cellSideMark.AddElement(phraseSideMark); cellSideMark.AddElement(new Paragraph(viewModel.SideMark, normal_font) { }); tableMark.AddCell(cellSideMark); var noImage = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z"; byte[] shippingMarkImage; if (String.IsNullOrEmpty(viewModel.ShippingMarkImageFile)) { viewModel.ShippingMarkImageFile = noImage; } if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile))) { shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)); Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage); if (shipMarkImage.Width > 60) { float percentage = 0.0f; percentage = 100 / shipMarkImage.Width; shipMarkImage.ScalePercent(percentage * 100); PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage); shipMarkImageCell.Border = Rectangle.NO_BORDER; tableMark.AddCell(shipMarkImageCell); } } byte[] sideMarkImage; if (String.IsNullOrEmpty(viewModel.SideMarkImageFile)) { viewModel.SideMarkImageFile = noImage; } if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile))) { sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)); Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage); if (_sideMarkImage.Width > 60) { float percentage = 0.0f; percentage = 100 / _sideMarkImage.Width; _sideMarkImage.ScalePercent(percentage * 100); } PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage); _sideMarkImageCell.Border = Rectangle.NO_BORDER; tableMark.AddCell(_sideMarkImageCell); } new PdfPCell(tableMark); tableMark.ExtendLastRow = false; tableMark.SpacingAfter = 5f; document.Add(tableMark); #endregion #region Measurement PdfPTable tableMeasurement = new PdfPTable(3); tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 12f }); PdfPCell cellMeasurement = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(viewModel.GrossWeight + " KGS", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(viewModel.NettWeight + " KGS", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase("NET NET WEIGHT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(viewModel.NetNetWeight + " KGS", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); PdfPTable tableMeasurementDetail = new PdfPTable(5); tableMeasurementDetail.SetWidths(new float[] { 1f, 1f, 1f, 1.5f, 2f }); PdfPCell cellMeasurementDetail = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; decimal totalCbm = 0; foreach (var measurement in viewModel.Measurements) { cellMeasurementDetail.Phrase = new Phrase(measurement.Length + " CM X ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(measurement.Width + " CM X ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(measurement.Height + " CM X ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000; totalCbm += cbm; cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N3} CBM", cbm), normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); } cellMeasurementDetail.Border = Rectangle.TOP_BORDER; cellMeasurementDetail.Phrase = new Phrase("", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N3} CBM", totalCbm), normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); new PdfPCell(tableMeasurementDetail); tableMeasurementDetail.ExtendLastRow = false; var paddingRight = SIZES_COUNT > 11 ? 400 : 200; tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail) { Border = Rectangle.NO_BORDER, PaddingRight = paddingRight }); tableMeasurement.AddCell(new PdfPCell { Border = Rectangle.NO_BORDER, Colspan = 3, Phrase = new Phrase("REMARK :", normal_font_underlined) }); tableMeasurement.AddCell(new PdfPCell { Border = Rectangle.NO_BORDER, Colspan = 3, Phrase = new Phrase(viewModel.Remark, normal_font) }); byte[] remarkImage; if (String.IsNullOrEmpty(viewModel.RemarkImageFile)) { viewModel.RemarkImageFile = noImage; } if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile))) { remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)); Image images = Image.GetInstance(imgb: remarkImage); if (images.Width > 60) { float percentage = 0.0f; percentage = 100 / images.Width; images.ScalePercent(percentage * 100); } PdfPCell imageCell = new PdfPCell(images); imageCell.Border = Rectangle.NO_BORDER; imageCell.Colspan = 3; tableMeasurement.AddCell(imageCell); } new PdfPCell(tableMeasurement); tableMeasurement.ExtendLastRow = false; tableMeasurement.SpacingAfter = 5f; document.Add(tableMeasurement); //document.Add(images); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
/** Shows a line of text. Only the first line is written. * @param canvas where the text is to be written to * @param alignment the alignment. It is not influenced by the run direction * @param phrase the <CODE>Phrase</CODE> with the text * @param x the x reference position * @param y the y reference position * @param rotation the rotation to be applied in degrees counterclockwise * @param runDirection the run direction * @param arabicOptions the options for the arabic shaping */ public static void ShowTextAligned(PdfContentByte canvas, int alignment, Phrase phrase, float x, float y, float rotation, int runDirection, int arabicOptions) { if (alignment != Element.ALIGN_LEFT && alignment != Element.ALIGN_CENTER && alignment != Element.ALIGN_RIGHT) alignment = Element.ALIGN_LEFT; canvas.SaveState(); ColumnText ct = new ColumnText(canvas); float lly = -1; float ury = 2; float llx; float urx; switch (alignment) { case Element.ALIGN_LEFT: llx = 0; urx = 20000; break; case Element.ALIGN_RIGHT: llx = -20000; urx = 0; break; default: llx = -20000; urx = 20000; break; } if (rotation == 0) { llx += x; lly += y; urx += x; ury += y; } else { double alpha = rotation * Math.PI / 180.0; float cos = (float)Math.Cos(alpha); float sin = (float)Math.Sin(alpha); canvas.ConcatCTM(cos, sin, -sin, cos, x, y); } ct.SetSimpleColumn(phrase, llx, lly, urx, ury, 2, alignment); if (runDirection == PdfWriter.RUN_DIRECTION_RTL) { if (alignment == Element.ALIGN_LEFT) alignment = Element.ALIGN_RIGHT; else if (alignment == Element.ALIGN_RIGHT) alignment = Element.ALIGN_LEFT; } ct.Alignment = alignment; ct.ArabicOptions = arabicOptions; ct.RunDirection = runDirection; ct.Go(); canvas.RestoreState(); }
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); }
/** 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; }
public NPages(PdfContentByte dc) { template = dc.CreateTemplate(50, 50); }
public void Cleanup(PdfContentByte cb) { int k = savedStates.Count; while (k-- > 0) cb.RestoreState(); }
public static void TransformTo(this PdfContentByte source, PdfTransformer transformer) { var matrix = transformer.GetMatrix(); source.AddTemplate(transformer.OriginPage, matrix); }
public void SaveState(PdfContentByte cb) { cb.SaveState(); MetaState state = new MetaState(this); savedStates.Push(state); }
/** 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); }
/** * @see com.lowagie.text.pdf.PdfPTableEvent#tableLayout(com.lowagie.text.pdf.PdfPTable, float[][], float[], int, int, com.lowagie.text.pdf.PdfContentByte[]) */ virtual public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) { foreach (IPdfPTableEvent eventa in events) { eventa.TableLayout(table, widths, heights, headerRows, rowStart, canvases); } }
/** * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[]) */ public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvases) { if (cellField == null || (fieldWriter == null && parent == null)) throw new ArgumentException("You have used the wrong constructor for this FieldPositioningEvents class."); cellField.Put(PdfName.RECT, new PdfRectangle(rect.GetLeft(padding), rect.GetBottom(padding), rect.GetRight(padding), rect.GetTop(padding))); if (parent == null) fieldWriter.AddAnnotation(cellField); else parent.AddKid(cellField); }
/** * @see com.lowagie.text.pdf.draw.DrawInterface#draw(com.lowagie.text.pdf.PdfContentByte, float, float, float, float, float) */ public virtual void Draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) { if (drawInterface != null) { drawInterface.Draw(canvas, llx, lly, urx, ury, y + offset); } }
private void AddPageWithRotationAndScaling(PdfContentByte documentPage, Rectangle documentPageSize, PdfImportedPage backgroundPage, Rectangle backgroundPageSize, int rotation) { float scaleWidth; float scaleHeight; float scale; float backgroundHeight; float backgroundWidth; switch (rotation) { case 90: scaleWidth = documentPageSize.Width / backgroundPageSize.Height; scaleHeight = documentPageSize.Height / backgroundPageSize.Width; scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight; backgroundHeight = scale * backgroundPageSize.Height; backgroundWidth = scale * backgroundPageSize.Width; documentPage.AddTemplate(backgroundPage, 0, -scale, scale, 0, (documentPageSize.Width - backgroundHeight) / 2, backgroundWidth + (documentPageSize.Height - backgroundWidth) / 2); break; case 180: scaleWidth = documentPageSize.Width / backgroundPageSize.Width; scaleHeight = documentPageSize.Height / backgroundPageSize.Height; scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight; backgroundHeight = scale * backgroundPageSize.Height; backgroundWidth = scale * backgroundPageSize.Width; documentPage.AddTemplate(backgroundPage, -scale, 0, 0, -scale, backgroundWidth + (documentPageSize.Width - backgroundWidth) / 2, backgroundHeight + (documentPageSize.Height - backgroundHeight) / 2); break; case 270: scaleWidth = documentPageSize.Width / backgroundPageSize.Height; scaleHeight = documentPageSize.Height / backgroundPageSize.Width; scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight; backgroundHeight = scale * backgroundPageSize.Height; backgroundWidth = scale * backgroundPageSize.Width; documentPage.AddTemplate(backgroundPage, 0, scale, -scale, 0, backgroundHeight + (documentPageSize.Width - backgroundHeight) / 2, (documentPageSize.Height - backgroundWidth) / 2); break; case 0: default: scaleWidth = documentPageSize.Width / backgroundPageSize.Width; scaleHeight = documentPageSize.Height / backgroundPageSize.Height; scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight; backgroundHeight = scale * backgroundPageSize.Height; backgroundWidth = scale * backgroundPageSize.Width; documentPage.AddTemplate(backgroundPage, scale, 0, 0, scale, (documentPageSize.Width - backgroundWidth) / 2, (documentPageSize.Height - backgroundHeight) / 2); break; } }