/** * Writes the border and background of one cell in the row. * @param xPos * @param yPos * @param cell * @param canvases */ public void WriteBorderAndBackground(float xPos, float yPos, PdfPCell cell, PdfContentByte[] canvases) { PdfContentByte lines = canvases[PdfPTable.LINECANVAS]; PdfContentByte backgr = canvases[PdfPTable.BACKGROUNDCANVAS]; // the coordinates of the border are retrieved float x1 = cell.Left + xPos; float y2 = cell.Top + yPos; float x2 = cell.Right + xPos; float y1 = y2 - maxHeight; // the backgroundcolor is set Color background = cell.BackgroundColor; if (background != null) { backgr.SetColorFill(background); backgr.Rectangle(x1, y1, x2 - x1, y2 - y1); backgr.Fill(); } // if the element hasn't got any borders, nothing is added if (cell.HasBorders()) { if (cell.UseVariableBorders) { Rectangle borderRect = new Rectangle(cell.Left + xPos, cell.Top - maxHeight + yPos, cell.Right + xPos, cell.Top + yPos); borderRect.CloneNonPositionParameters(cell); borderRect.BackgroundColor = null; lines.Rectangle(borderRect); } else { // the width is set to the width of the element if (cell.BorderWidth != Rectangle.UNDEFINED) { lines.SetLineWidth(cell.BorderWidth); } // the color is set to the color of the element Color color = cell.BorderColor; if (color != null) { lines.SetColorStroke(color); } // if the box is a rectangle, it is added as a rectangle if (cell.HasBorder(Rectangle.BOX)) { lines.Rectangle(x1, y1, x2 - x1, y2 - y1); } // if the border isn't a rectangle, the different sides are // added apart else { if (cell.HasBorder(Rectangle.RIGHT_BORDER)) { lines.MoveTo(x2, y1); lines.LineTo(x2, y2); } if (cell.HasBorder(Rectangle.LEFT_BORDER)) { lines.MoveTo(x1, y1); lines.LineTo(x1, y2); } if (cell.HasBorder(Rectangle.BOTTOM_BORDER)) { lines.MoveTo(x1, y1); lines.LineTo(x2, y1); } if (cell.HasBorder(Rectangle.TOP_BORDER)) { lines.MoveTo(x1, y2); lines.LineTo(x2, y2); } } lines.Stroke(); if (color != null) { lines.ResetRGBColorStroke(); } } } }
/** 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; if (font != null) { if (generateChecksum && checksumText) { fullCode += GetChecksum(fullCode); } if (startStopText) { fullCode = "*" + fullCode + "*"; } fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } string bCode = code; if (extended) { bCode = GetCode39Ex(code); } if (generateChecksum) { bCode += GetChecksum(bCode); } int len = bCode.Length + 2; float fullWidth = len * (6 * x + 3 * x * n) + (len - 1) * x; float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) { barStartX = fontX - fullWidth; } else { textStartX = fullWidth - fontX; } break; default: if (fontX > fullWidth) { barStartX = (fontX - fullWidth) / 2; } else { textStartX = (fullWidth - fontX) / 2; } break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) { textStartY = barHeight - baseline; } else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } byte[] bars = GetBarsCode39(bCode); bool print = true; if (barColor != null) { cb.SetColorFill(barColor); } for (int k = 0; k < bars.Length; ++k) { float w = (bars[k] == 0 ? x : x * n); if (print) { cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) { cb.SetColorFill(textColor); } cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return(this.BarcodeSize); }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { Rectangle rect = this.BarcodeSize; float barStartX = 0; float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) { textStartY = barHeight - baseline; } else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } switch (codeType) { case EAN13: case UPCA: case UPCE: if (font != null) { barStartX += font.GetWidthPoint(code[0], size); } break; } byte[] bars = null; int[] guard = GUARD_EMPTY; switch (codeType) { case EAN13: bars = GetBarsEAN13(code); guard = GUARD_EAN13; break; case EAN8: bars = GetBarsEAN8(code); guard = GUARD_EAN8; break; case UPCA: bars = GetBarsEAN13("0" + code); guard = GUARD_UPCA; break; case UPCE: bars = GetBarsUPCE(code); guard = GUARD_UPCE; break; case SUPP2: bars = GetBarsSupplemental2(code); break; case SUPP5: bars = GetBarsSupplemental5(code); break; } float keepBarX = barStartX; bool print = true; float gd = 0; if (font != null && baseline > 0 && guardBars) { gd = baseline / 2; } if (barColor != null) { cb.SetColorFill(barColor); } for (int k = 0; k < bars.Length; ++k) { float w = bars[k] * x; if (print) { if (Array.BinarySearch(guard, k) >= 0) { cb.Rectangle(barStartX, barStartY - gd, w - inkSpreading, barHeight + gd); } else { cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) { cb.SetColorFill(textColor); } cb.BeginText(); cb.SetFontAndSize(font, size); switch (codeType) { case EAN13: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 13; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case EAN8: for (int k = 0; k < 8; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = TEXTPOS_EAN8[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case UPCA: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 11; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (11 + 12 * 7), textStartY); cb.ShowText(code.Substring(11, 1)); break; case UPCE: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 7; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (9 + 6 * 7), textStartY); cb.ShowText(code.Substring(7, 1)); break; case SUPP2: case SUPP5: for (int k = 0; k < code.Length; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = (7.5f + (9 * k)) * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; } cb.EndText(); } return(rect); }
/** 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); }
/** 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; if (generateChecksum && checksumText) { fullCode = CalculateChecksum(code); } if (!startStopText) { fullCode = fullCode.Substring(1, fullCode.Length - 2); } float fontX = 0; if (font != null) { fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } byte[] bars = GetBarsCodabar(generateChecksum ? CalculateChecksum(code) : code); int wide = 0; for (int k = 0; k < bars.Length; ++k) { wide += (int)bars[k]; } int narrow = bars.Length - wide; float fullWidth = x * (narrow + wide * n); float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) { barStartX = fontX - fullWidth; } else { textStartX = fullWidth - fontX; } break; default: if (fontX > fullWidth) { barStartX = (fontX - fullWidth) / 2; } else { textStartX = (fullWidth - fontX) / 2; } break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) { textStartY = barHeight - baseline; } else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } bool print = true; if (barColor != null) { cb.SetColorFill(barColor); } for (int k = 0; k < bars.Length; ++k) { float w = (bars[k] == 0 ? x : x * n); if (print) { cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) { cb.SetColorFill(textColor); } cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return(BarcodeSize); }
public override void OnStartPage(PdfWriter writer, Document document) { base.OnStartPage(writer, document); //Fill light gray body background cb.SetColorStroke(new BaseColor(Color.FromArgb(212, 222, 223))); cb.SetColorFill(new BaseColor(Color.FromArgb(212, 222, 223))); cb.MoveTo(15, 800); cb.LineTo(580, 800); cb.LineTo(580, 10); cb.LineTo(15, 10); cb.Fill(); //Header table fonts iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font headerFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.WHITE); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font headerFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.WHITE); //Create header table PdfPTable headerTable = new PdfPTable(3); iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(_headerImageURL); PdfPCell logoCell = new PdfPCell(logo); logoCell.HorizontalAlignment = Element.ALIGN_CENTER; Phrase officeName = new Phrase(_headerText, headerFontNormal); //Create Header table row 1 cells PdfPCell headerRow1Cell1 = new PdfPCell(); PdfPCell headerRow1Cell2 = new PdfPCell(logoCell); PdfPCell headerRow1Cell3 = new PdfPCell(); String text = "Page " + writer.PageNumber + " of "; //Create Header table row 2 cells PdfPCell headerRow2ColspanCell = new PdfPCell(officeName); //Create Header table row 3 cells PdfPCell headerRow3Cell1 = new PdfPCell(new Phrase("Date: " + printDateTime.ToString("d MMM yyyy", System.Globalization.CultureInfo.InvariantCulture), headerFontBig)); PdfPCell headerRow3Cell2 = new PdfPCell(); PdfPCell headerRow3Cell3 = new PdfPCell(new Phrase("TIME: " + string.Format("{0:T}", DateTime.Now, System.Globalization.CultureInfo.InvariantCulture), headerFontBig)); //Set the background color of all Header table cells headerRow1Cell1.BackgroundColor = new BaseColor(Color.FromArgb(40, 40, 40)); headerRow1Cell2.BackgroundColor = new BaseColor(Color.FromArgb(40, 40, 40)); headerRow1Cell3.BackgroundColor = new BaseColor(Color.FromArgb(40, 40, 40)); headerRow2ColspanCell.BackgroundColor = new BaseColor(Color.FromArgb(40, 40, 40)); headerRow3Cell1.BackgroundColor = new BaseColor(Color.FromArgb(40, 40, 40)); headerRow3Cell2.BackgroundColor = new BaseColor(Color.FromArgb(40, 40, 40)); headerRow3Cell3.BackgroundColor = new BaseColor(Color.FromArgb(40, 40, 40)); //Set the horizontal alignment of all three Header table cells headerRow1Cell1.HorizontalAlignment = Element.ALIGN_CENTER; headerRow1Cell2.HorizontalAlignment = Element.ALIGN_CENTER; headerRow1Cell3.HorizontalAlignment = Element.ALIGN_CENTER; headerRow2ColspanCell.HorizontalAlignment = Element.ALIGN_CENTER; headerRow3Cell1.HorizontalAlignment = Element.ALIGN_CENTER; headerRow3Cell2.HorizontalAlignment = Element.ALIGN_CENTER; headerRow3Cell3.HorizontalAlignment = Element.ALIGN_CENTER; //Set the vertical alignment of all three Header table cells headerRow1Cell2.VerticalAlignment = Element.ALIGN_BOTTOM; headerRow1Cell3.VerticalAlignment = Element.ALIGN_MIDDLE; headerRow2ColspanCell.VerticalAlignment = Element.ALIGN_TOP; headerRow3Cell1.VerticalAlignment = Element.ALIGN_MIDDLE; headerRow3Cell2.VerticalAlignment = Element.ALIGN_MIDDLE; headerRow3Cell3.VerticalAlignment = Element.ALIGN_MIDDLE; headerRow2ColspanCell.Colspan = 3; //Set the border of all three Header table cells to 0 headerRow1Cell1.Border = 0; headerRow1Cell2.Border = 0; headerRow1Cell3.Border = 0; headerRow2ColspanCell.Border = 0; headerRow3Cell1.Border = 0; headerRow3Cell2.Border = 0; headerRow3Cell3.Border = 0; //Add all cells into Header table headerTable.AddCell(headerRow1Cell1); headerTable.AddCell(headerRow1Cell2); headerTable.AddCell(headerRow1Cell3); headerTable.AddCell(headerRow2ColspanCell); headerTable.AddCell(headerRow3Cell1); headerTable.AddCell(headerRow3Cell2); headerTable.AddCell(headerRow3Cell3); //Header table width and position headerTable.TotalWidth = document.PageSize.Width; headerTable.WriteSelectedRows(0, -1, 0, (document.PageSize.Height), writer.DirectContent); }
/** 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; }
/// <summary> /// Places the barcode in a PdfContentByte . The /// barcode is always placed at coodinates (0, 0). Use the /// translation matrix to move it elsewhere. /// The bars and text are written in the following colors: /// /// /// barColor /// textColor /// Result /// /// /// null /// null /// bars and text painted with current fill color /// /// /// barColor /// null /// bars and text painted with barColor /// /// /// null /// textColor /// bars painted with current color text painted with textColor /// /// /// barColor /// textColor /// bars painted with barColor text painted with textColor /// /// /// </summary> /// <param name="cb">the PdfContentByte where the barcode will be placed</param> /// <param name="barColor">the color of the bars. It can be null </param> /// <param name="textColor">the color of the text. It can be null </param> /// <returns>the dimensions the barcode occupies</returns> public override Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) { var rect = BarcodeSize; float barStartX = 0; float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) { textStartY = barHeight - baseline; } else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } switch (codeType) { case EAN13: case UPCA: case UPCE: if (font != null) { barStartX += font.GetWidthPoint(code[0], size); } break; } byte[] bars = null; var guard = _guardEmpty; switch (codeType) { case EAN13: bars = GetBarsEan13(code); guard = _guardEan13; break; case EAN8: bars = GetBarsEan8(code); guard = _guardEan8; break; case UPCA: bars = GetBarsEan13($"0{code}"); guard = _guardUpca; break; case UPCE: bars = GetBarsUpce(code); guard = _guardUpce; break; case SUPP2: bars = GetBarsSupplemental2(code); break; case SUPP5: bars = GetBarsSupplemental5(code); break; } var keepBarX = barStartX; var print = true; float gd = 0; if (font != null && baseline > 0 && guardBars) { gd = baseline / 2; } if (barColor != null) { cb.SetColorFill(barColor); } for (var k = 0; k < bars.Length; ++k) { var w = bars[k] * x; if (print) { if (Array.BinarySearch(guard, k) >= 0) { cb.Rectangle(barStartX, barStartY - gd, w - inkSpreading, barHeight + gd); } else { cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) { cb.SetColorFill(textColor); } cb.BeginText(); cb.SetFontAndSize(font, size); switch (codeType) { case EAN13: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (var k = 1; k < 13; ++k) { var c = code.Substring(k, 1); var len = font.GetWidthPoint(c, size); var pX = keepBarX + _textposEan13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case EAN8: for (var k = 0; k < 8; ++k) { var c = code.Substring(k, 1); var len = font.GetWidthPoint(c, size); var pX = _textposEan8[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case UPCA: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (var k = 1; k < 11; ++k) { var c = code.Substring(k, 1); var len = font.GetWidthPoint(c, size); var pX = keepBarX + _textposEan13[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (11 + 12 * 7), textStartY); cb.ShowText(code.Substring(11, 1)); break; case UPCE: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (var k = 1; k < 7; ++k) { var c = code.Substring(k, 1); var len = font.GetWidthPoint(c, size); var pX = keepBarX + _textposEan13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (9 + 6 * 7), textStartY); cb.ShowText(code.Substring(7, 1)); break; case SUPP2: case SUPP5: for (var k = 0; k < code.Length; ++k) { var c = code.Substring(k, 1); var len = font.GetWidthPoint(c, size); var pX = (7.5f + (9 * k)) * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; } cb.EndText(); } return(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 override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { Rectangle rect = this.BarcodeSize; float barStartX = 0; float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) textStartY = barHeight - baseline; else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } switch (codeType) { case EAN13: case UPCA: case UPCE: if (font != null) barStartX += font.GetWidthPoint(code[0], size); break; } byte[] bars = null; int[] guard = GUARD_EMPTY; switch (codeType) { case EAN13: bars = GetBarsEAN13(code); guard = GUARD_EAN13; break; case EAN8: bars = GetBarsEAN8(code); guard = GUARD_EAN8; break; case UPCA: bars = GetBarsEAN13("0" + code); guard = GUARD_UPCA; break; case UPCE: bars = GetBarsUPCE(code); guard = GUARD_UPCE; break; case SUPP2: bars = GetBarsSupplemental2(code); break; case SUPP5: bars = GetBarsSupplemental5(code); break; } float keepBarX = barStartX; bool print = true; float gd = 0; if (font != null && baseline > 0 && guardBars) { gd = baseline / 2; } if (barColor != null) cb.SetColorFill(barColor); for (int k = 0; k < bars.Length; ++k) { float w = bars[k] * x; if (print) { if (Array.BinarySearch(guard, k) >= 0) cb.Rectangle(barStartX, barStartY - gd, w - inkSpreading, barHeight + gd); else cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); } print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) cb.SetColorFill(textColor); cb.BeginText(); cb.SetFontAndSize(font, size); switch (codeType) { case EAN13: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 13; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case EAN8: for (int k = 0; k < 8; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = TEXTPOS_EAN8[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; case UPCA: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 11; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (11 + 12 * 7), textStartY); cb.ShowText(code.Substring(11, 1)); break; case UPCE: cb.SetTextMatrix(0, textStartY); cb.ShowText(code.Substring(0, 1)); for (int k = 1; k < 7; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = keepBarX + TEXTPOS_EAN13[k - 1] * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } cb.SetTextMatrix(keepBarX + x * (9 + 6 * 7), textStartY); cb.ShowText(code.Substring(7, 1)); break; case SUPP2: case SUPP5: for (int k = 0; k < code.Length; ++k) { string c = code.Substring(k, 1); float len = font.GetWidthPoint(c, size); float pX = (7.5f + (9 * k)) * x - len / 2; cb.SetTextMatrix(pX, textStartY); cb.ShowText(c); } break; } cb.EndText(); } return rect; }
// --------------------------------------------------------------------------- /** * Creates a PDF document for PdfReader. */ public byte[] CreatePdf() { // step 1 using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30)) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 PdfContentByte under = writer.DirectContentUnder; // Page 1: a rectangle DrawRectangle( under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height ); under.SetRGBColorFill(0xFF, 0xD7, 0x00); under.Rectangle( 5, 5, PageSize.POSTCARD.Width - 10, PageSize.POSTCARD.Height - 10 ); under.Fill(); document.NewPage(); // Page 2: an image DrawRectangle( under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height ); Image img = Image.GetInstance(Path.Combine( Utility.ResourceImage, "loa.jpg" )); img.SetAbsolutePosition( (PageSize.POSTCARD.Width - img.ScaledWidth) / 2, (PageSize.POSTCARD.Height - img.ScaledHeight) / 2 ); document.Add(img); document.NewPage(); // Page 3: the words "Foobar Film Festival" DrawRectangle( under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height ); Paragraph p = new Paragraph( "Foobar Film Festival", new Font(Font.FontFamily.HELVETICA, 22) ); p.Alignment = Element.ALIGN_CENTER; document.Add(p); document.NewPage(); // Page 4: the words "SOLD OUT" DrawRectangle(under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height); PdfContentByte over = writer.DirectContent; over.SaveState(); float sinus = (float)Math.Sin(Math.PI / 60); float cosinus = (float)Math.Cos(Math.PI / 60); BaseFont bf = BaseFont.CreateFont(); over.BeginText(); over.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); over.SetLineWidth(1.5f); over.SetRGBColorStroke(0xFF, 0x00, 0x00); over.SetRGBColorFill(0xFF, 0xFF, 0xFF); over.SetFontAndSize(bf, 36); over.SetTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324); over.ShowText("SOLD OUT"); over.SetTextMatrix(0, 0); over.EndText(); over.RestoreState(); } return(ms.ToArray()); } }
public byte[] DownloadObservation( int branchId, int?locationId, DateTime?fromDate, DateTime?toDate, IHostingEnvironment _hostingEnvironment ) { try { var observationReportData = _activityService.GetObservationReport(branchId, locationId, fromDate, toDate); var memoryStream = new System.IO.MemoryStream(); // var document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(288f, 432f)); Document document = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10); PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); Phrase phrase = new Phrase(); document.Add(phrase); var path = Path.Combine(_hostingEnvironment.WebRootPath, @"images\Eco.jpg"); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path); image.ScaleAbsolute(120f, 60f); image.SetAbsolutePosition(8f, 530f); image.Alignment = iTextSharp.text.Element.ALIGN_CENTER; //image.SpacingAfter = 40; document.Add(image); PdfContentByte cb = writer.DirectContent; //var Rectangular = new iTextSharp.text.Rectangle(7, 420, 280, 25); //left width,top height,right width,bottom height //Rectangular.BorderWidthLeft = 1.1f; //Rectangular.BorderWidthRight = 1.1f; //Rectangular.BorderWidthTop = 1.1f; //Rectangular.BorderWidthBottom = 1.1f; var blackListTextFont = (BaseColor.Black); //cb.Rectangle(Rectangular); //cb.Stroke(); var companyname = observationReportData.Select(i => i.CompanyName).FirstOrDefault(); var branchname = observationReportData.Select(a => a.BranchName).FirstOrDefault(); cb.SetLineWidth(1); cb.Rectangle(135, 510, 840, 85); //left width,bottom height,right width,top height cb.BeginText(); BaseFont f_cn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetFontAndSize(f_cn, 18); cb.SetColorFill(BaseColor.LightGray); cb.Fill(); cb.EndText(); PdfContentByte cb1 = writer.DirectContent; cb1.SetLineWidth(1); //cb1.Rectangle(95, 510, 840, 80); //left width,bottom height,right width,top height cb1.BeginText(); BaseFont f_cnn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb1.SetFontAndSize(f_cn, 18); cb1.SetColorFill(BaseColor.White); cb1.SetTextMatrix(160, 565); cb1.ShowText(companyname + " " + branchname); cb1.Fill(); cb1.EndText(); PdfContentByte cb2 = writer.DirectContent; cb2.SetLineWidth(1); //cb1.Rectangle(95, 510, 840, 80); //left width,bottom height,right width,top height cb2.BeginText(); BaseFont f_cnnn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb2.SetFontAndSize(f_cn, 18); cb2.SetColorFill(BaseColor.White); cb2.SetTextMatrix(650, 565); cb2.ShowText("ObservationReport"); // cb2.SetTextMatrix(25, 125); cb2.Fill(); cb2.EndText(); PdfContentByte cb3 = writer.DirectContent; cb3.SetLineWidth(1); //cb1.Rectangle(95, 510, 840, 80); //left width,bottom height,right width,top height cb3.BeginText(); BaseFont f_cnnnn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb3.SetFontAndSize(f_cn, 15); cb3.SetColorFill(BaseColor.Black); cb3.SetTextMatrix(160, 525); cb3.ShowText("Report Period"); // cb2.SetTextMatrix(25, 125); cb3.Fill(); cb3.EndText(); iTextSharp.text.Paragraph company = new iTextSharp.text.Paragraph(); iTextSharp.text.Paragraph branch = new iTextSharp.text.Paragraph(); company.SpacingBefore = 10; company.SpacingAfter = 25; company.Alignment = iTextSharp.text.Element.ALIGN_CENTER; company.Font = FontFactory.GetFont(FontFactory.TIMES, 20f, BaseColor.Black); company.Add("Company: " + companyname + " " + "Branch: " + branchname); document.Add(company); //PdfContentByte cb1 = writer.DirectContent; ////cb.MoveTo(document.PageSize.Width / 2, document.PageSize.Height / 2); ////cb.LineTo(document.PageSize.Width / 2, document.PageSize.Height); ////cb.Stroke(); //cb.MoveTo(0, document.PageSize.Height / 1.15f); //cb.LineTo(document.PageSize.Width, document.PageSize.Height / 1.15f); //cb.Stroke(); PdfPTable table = new PdfPTable(7); PdfPCell cell = new PdfPCell(); table.SpacingBefore = 70; table.WidthPercentage = 100; table.DefaultCell.Border = Table.NO_BORDER; //cell.Phrase = new Phrase("Observation No"); //table.AddCell(cell); var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12); cell.Phrase = new Phrase("ObservationDate", boldFont); table.AddCell(cell); cell.Phrase = new Phrase("StationName", boldFont); table.AddCell(cell); //cell.Phrase = new Phrase("StationNo", boldFont); //table.AddCell(cell); cell.Phrase = new Phrase("Location", boldFont); table.AddCell(cell); cell.Phrase = new Phrase("Observation Description", boldFont); table.AddCell(cell); //cell.Phrase = new Phrase("Action On Client End", boldFont); //table.AddCell(cell); cell.Phrase = new Phrase("Images", boldFont); table.AddCell(cell); cell.Phrase = new Phrase("Date Of Client End", boldFont); table.AddCell(cell); cell.Phrase = new Phrase("Status", boldFont); table.AddCell(cell); foreach (var observation in observationReportData) { cell.Phrase = new Phrase(observation.ObservationDate); table.AddCell(cell); cell.Phrase = new Phrase(observation.StationName); table.AddCell(cell); //cell.Phrase = new Phrase(observation.StationId); //table.AddCell(cell); cell.Phrase = new Phrase(observation.LocationName); table.AddCell(cell); cell.Phrase = new Phrase(observation.Description); table.AddCell(cell); cell.Phrase = new Phrase(observation.Images); table.AddCell(cell); //cell.Phrase = new Phrase(observation.ClientReview); //table.AddCell(cell); cell.Phrase = new Phrase(observation.ClientReviewDate.ToString()); table.AddCell(cell); cell.Phrase = new Phrase(observation.Status); table.AddCell(cell); } document.Add(table); document.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); return(bytes); } catch (Exception e) { Console.WriteLine(e); throw e; } }
public void ToPDF(iTextSharp.text.pdf.PdfWriter w) { PdfContentByte cb = w.DirectContent; cb.SetLineWidth((float)Settings.Thickness); if (Settings.Fill != null) { cb.SetColorFill(Settings.Fill.ToPDFColor()); } if (Settings.Stroke != null) { cb.SetColorStroke(Settings.Stroke.ToPDFColor()); } if (Geometry.GetType() == typeof(Dyn.Arc)) { Dyn.Arc arc = Geometry as Dyn.Arc; cb.MoveTo(arc.StartPoint.X, arc.EndPoint.Y); cb.CurveTo(arc.PointAtParameter(0.5).X, arc.PointAtParameter(0.5).Y, arc.EndPoint.X, arc.EndPoint.Y); } else if (Geometry.GetType() == typeof(Dyn.Line)) { Dyn.Line line = Geometry as Dyn.Line; cb.MoveTo(line.StartPoint.X, line.StartPoint.Y); cb.LineTo(line.EndPoint.X, line.EndPoint.Y); } else if (Geometry.GetType() == typeof(Dyn.Circle)) { Dyn.Circle circle = Geometry as Dyn.Circle; cb.Circle(circle.CenterPoint.X, circle.CenterPoint.Y, circle.Radius); } else if (Geometry.GetType() == typeof(Dyn.Ellipse)) { Dyn.Ellipse ellipse = Geometry as Dyn.Ellipse; cb.Ellipse(ellipse.StartPoint.X, ellipse.StartPoint.Y, ellipse.EndPoint.X, ellipse.EndPoint.Y); } else if (Geometry.GetType() == typeof(Dyn.Rectangle)) { Dyn.Rectangle rect = Geometry as Dyn.Rectangle; cb.Rectangle(rect.Center().X, rect.Center().Y, rect.Width, rect.Height); } else if (Geometry.GetType() == typeof(Dyn.Polygon)) { Dyn.Polygon p = Geometry as Dyn.Polygon; foreach (var curve in p.Curves()) { CurveToPDF(curve, cb); } } else if (Geometry.GetType() == typeof(Dyn.PolyCurve)) { Dyn.PolyCurve pc = Geometry as Dyn.PolyCurve; foreach (var curve in pc.Curves()) { CurveToPDF(curve, cb); } } else if (Geometry.GetType() == typeof(Dyn.NurbsCurve)) { Dyn.NurbsCurve nc = Geometry as Dyn.NurbsCurve; foreach (var linearc in nc.ApproximateWithArcAndLineSegments()) { CurveToPDF(linearc, cb); } } else if (Geometry.GetType() == typeof(Dyn.Curve)) { Dyn.Curve curve = Geometry as Dyn.Curve; CurveToPDF(curve, cb); } else { throw new Exception(Properties.Resources.NotSupported); } if (Settings.Fill != null && Settings.Stroke != null) { cb.FillStroke(); } else { if (Settings.Stroke != null) { cb.Stroke(); } if (Settings.Fill != null) { cb.Fill(); } } }
public static void Barras(PdfContentByte cb, ArrayList valores, ArrayList labels, float y0, float max) { float h = PageSize.LETTER.Width; // paisagem float w = PageSize.LETTER.Height; cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10); cb.MoveTo(110, h - 10 - y0); cb.LineTo(110, h - 320 - y0); for (int y = 320; y >= 20; y -= 30) { cb.MoveTo(100, h - y - y0); cb.LineTo(620, h - y - y0); } for (int x = 110; x <= 620; x += 40) { cb.MoveTo(x, h - 320 - y0); cb.LineTo(x, h - 325 - y0); } cb.FillStroke(); float vlr = 100; while (vlr < max) { vlr *= 2; } float d = vlr / 10; vlr = 0; for (int y = 320; y >= 20; y -= 30) { cb.BeginText(); cb.SetTextMatrix(10, h - y - y0); cb.ShowText(vlr.ToString("###,###,##0.00").PadLeft(14)); vlr += d; cb.EndText(); } int[,] cores = new int[, ] { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 }, { 255, 255, 0 }, { 255, 0, 255 }, { 0, 255, 255 }, { 255, 128, 0 }, { 0, 255, 128 }, { 128, 0, 255 }, { 255, 128, 128 }, { 128, 255, 128 }, { 128, 128, 255 } }; int i = 0; foreach (float valor in valores) { Legenda(cb, i, valor, labels[i].ToString(), cores, 500, y0, 0); i++; } i = 0; int x1 = 115; int y1; foreach (string descricao in labels) { int j = 0; string valor = ""; foreach (float v in valores) { valor = v.ToString("#,###,##0.00"); if (j++ == i) { break; } } cb.SetRGBColorFill(cores[i, 0], cores[i, 1], cores[i, 2]); y1 = (int)(Globais.StrToFloat(valor) / d * 30); cb.Rectangle(x1, h - y0 - 319, 30, y1); cb.Fill(); x1 += 40; i++; } }
public void OutputText(int x, int y, int flag, int x1, int y1, int x2, int y2, string text) { MetaFont font = _state.CurrentFont; float refX = _state.TransformX(x); float refY = _state.TransformY(y); float angle = _state.TransformAngle(font.Angle); float sin = (float)Math.Sin(angle); float cos = (float)Math.Cos(angle); float fontSize = font.GetFontSize(_state); BaseFont bf = font.Font; int align = _state.TextAlign; float textWidth = bf.GetWidthPoint(text, fontSize); float tx = 0; float ty = 0; float descender = bf.GetFontDescriptor(BaseFont.DESCENT, fontSize); float ury = bf.GetFontDescriptor(BaseFont.BBOXURY, fontSize); Cb.SaveState(); Cb.ConcatCtm(cos, sin, -sin, cos, refX, refY); if ((align & MetaState.TaCenter) == MetaState.TaCenter) { tx = -textWidth / 2; } else if ((align & MetaState.TaRight) == MetaState.TaRight) { tx = -textWidth; } if ((align & MetaState.TaBaseline) == MetaState.TaBaseline) { ty = 0; } else if ((align & MetaState.TaBottom) == MetaState.TaBottom) { ty = -descender; } else { ty = -ury; } BaseColor textColor; if (_state.BackgroundMode == MetaState.Opaque) { textColor = _state.CurrentBackgroundColor; Cb.SetColorFill(textColor); Cb.Rectangle(tx, ty + descender, textWidth, ury - descender); Cb.Fill(); } textColor = _state.CurrentTextColor; Cb.SetColorFill(textColor); Cb.BeginText(); Cb.SetFontAndSize(bf, fontSize); Cb.SetTextMatrix(tx, ty); Cb.ShowText(text); Cb.EndText(); if (font.IsUnderline()) { Cb.Rectangle(tx, ty - fontSize / 4, textWidth, fontSize / 15); Cb.Fill(); } if (font.IsStrikeout()) { Cb.Rectangle(tx, ty + fontSize / 3, textWidth, fontSize / 15); Cb.Fill(); } Cb.RestoreState(); }
/// <summary> /// Add a filled rectangle /// </summary> /// <returns></returns> private void addFillRectangle(float x, float y, float width, float height, Color color) { pdfContent.SetColorFill(new BaseColor(color)); pdfContent.Rectangle(x, pageHeight - y - height, width, height); pdfContent.Fill(); }
private bool CreatePlayersPDF(string outputPDFPath) { int bmpIndex; float prec, radius; Document outputDocument = null; PdfWriter pdfWriter = null; PdfReader templatePDF = null; PdfContentByte contentByte = null; try { templatePDF = new PdfReader(Application.StartupPath + "//Data//PDF//Ludo_PDF//Ludo_Players.pdf"); outputDocument = new iTextSharp.text.Document(templatePDF.GetPageSize(1)); outputDocument.SetMargins(0f, 0f, 0f, 0f); // Create the pdf writer pdfWriter = PdfWriter.GetInstance(outputDocument, new FileStream(outputPDFPath, FileMode.Create, FileAccess.Write)); // Open the pdf document outputDocument.Open(); // Draw the corner dots contentByte = pdfWriter.DirectContent; for (int i = 0; i < 2; i++) { // Place players images for (int j = 0; j < 4 * m_images.Length; j++) { bmpIndex = j % m_images.Length; // Scale image prec = PLAYER_IMAGE_WIDTH / m_images[bmpIndex].Width; m_images[bmpIndex].ScalePercent(prec * 100); // Add image m_images[bmpIndex].SetAbsolutePosition( 169.2f + (bmpIndex * (m_images[bmpIndex].ScaledWidth + HORIZ_GAP)), 678f - ((j / m_images.Length) * (m_images[bmpIndex].ScaledHeight + VERT_GAP))); contentByte.AddImage(m_images[bmpIndex]); } // Set the dots radius radius = 5.5f / 2.0f; // BOTTOM LEFT contentByte.Circle(167.8f + radius, 194.2f + radius, radius); contentByte.Fill(); // TOP LEFT contentByte.Circle(171.8f + radius, 812.4f + radius, radius); contentByte.Fill(); // TOP RIGHT contentByte.Circle(549.4f + radius, 819.1f + radius, radius); contentByte.Fill(); // BOTTOM RIGHT contentByte.Circle(510.7f + radius, 196.8f + radius, radius); contentByte.Fill(); if (i + 1 < 2) { outputDocument.NewPage(); } } // Close the document outputDocument.Close(); } catch (iTextSharp.text.DocumentException err) { MessageBox.Show(err.Message, m_cropperForm.m_langDictionary["Create PDF"], MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } finally { // Clean up outputDocument = null; } return(true); }
/// <summary> /// 產生barcode PDF /// </summary> protected void BarcodePDF() { try { var logistics = new POS_Library.ShopPos.LogisticsAccount(); LDList = logistics.GetLogisticsDetail(id); var LBList = logistics.GetBarcode(id); //if有找到資料 if (LDList.Count > 0) { //宣告文件doc1 Document doc1 = new Document(PageSize.A4, 20, 20, 40, 20); MemoryStream Memory = new MemoryStream(); PdfWriter PdfWriter = PdfWriter.GetInstance(doc1, Memory); //建立中文字型 BaseFont bfChinese = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\mingliu.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //開始編輯doc1 doc1.Open(); //取得內容物件DirectContent PdfContentByte PCB = PdfWriter.DirectContent; //啟用PCB PCB.SaveState(); PCB.BeginText(); PCB.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); PCB.SetFontAndSize(bfChinese, 14); float offset_xi = 50, offset_yi = 800; for (int i = 0; i < 10; i++) { switch (i) { case 0: offset_xi = 60; offset_yi = 770; break; case 1: offset_xi = 285; offset_yi = 770; break; case 2: offset_xi = 60; offset_yi = 630; break; case 3: offset_xi = 285; offset_yi = 630; break; case 4: offset_xi = 60; offset_yi = 490; break; case 5: offset_xi = 285; offset_yi = 490; break; case 6: offset_xi = 60; offset_yi = 350; break; case 7: offset_xi = 285; offset_yi = 350; break; case 8: offset_xi = 60; offset_yi = 210; break; case 9: offset_xi = 285; offset_yi = 210; break; } //設定帳號及圖片位置 PCB.ShowTextAligned(0, LDList[0].Account, offset_xi, offset_yi, 0); iTextSharp.text.Image img; img = iTextSharp.text.Image.GetInstance(LBList[0].ImageSource); img.ScalePercent(80, 40); img.SetAbsolutePosition(offset_xi - 35, offset_yi - 70); PCB.AddImage(img); } PCB.EndText(); //畫格線 PCB.SetRGBColorFill(0x00, 0x00, 0x00); //上下兩條橫線 PCB.Rectangle(30, 810, 450, 1); PCB.Fill(); PCB.Rectangle(30, 109, 450, 1); PCB.Fill(); //三條垂直線 PCB.Rectangle(30, 110, 1, 700); PCB.Fill(); PCB.Rectangle(480, 109, 1, 702); PCB.Fill(); PCB.Rectangle(255, 110, 1, 701); PCB.Fill(); //中間四條橫線 PCB.Rectangle(30, 249, 450, 1); PCB.Fill(); PCB.Rectangle(30, 389, 450, 1); PCB.Fill(); PCB.Rectangle(30, 529, 450, 1); PCB.Fill(); PCB.Rectangle(30, 669, 450, 1); PCB.Fill(); //關閉PCB //PCB.EndText(); PCB.RestoreState(); doc1.Close(); Response.Clear(); Response.AddHeader("Content-Disposition", "attachment;filename=logistics_account_barcode_" + id + ".pdf"); Response.ContentType = "application/octet-stream"; Response.OutputStream.Write(Memory.GetBuffer(), 0, Memory.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.Flush(); Response.End(); } } catch (Exception ex) { Response.Write("系統發生錯誤 " + ex.Message); } }
public void writePage(Page pPage) { // page size is given per <fotobook/page>. iTextSharp needs it set before adding page or opening document. _doc.SetPageSize(new Rectangle(0f, 0f, pPage.bundleSize.X, pPage.bundleSize.Y)); // handle first page case try { if (!_doc.IsOpen()) { _doc.Open(); } else { _doc.NewPage(); } } catch (Exception e) { Log.Error("Creating pdf page failed with error: '" + e.Message + "'."); return; } PdfContentByte canvas = _writer.DirectContent; // TOOD: de-duplicate // draw left part of background if (pPage.backgroundLeft != null) { canvas.Rectangle(0, 0, pPage.bundleSize.X / 2, pPage.bundleSize.Y); #if DEBUG || _DEBUG canvas.SetColorFill(BaseColor.CYAN); #else canvas.SetColorFill(BaseColor.WHITE); #endif canvas.Fill(); string id = pPage.backgroundLeft; System.Drawing.Image sysImg = DesignIdConverter.getImageFromID(id); if (sysImg == null) { Log.Error("Background image for id '" + id + "' was null."); #if DEBUG || _DEBUG canvas.SetColorFill(BaseColor.MAGENTA); #else canvas.SetColorFill(BaseColor.WHITE); #endif canvas.Fill(); } else { Image img = sysImageToITextImage(sysImg); float facY = pPage.bundleSize.Y / img.PlainHeight; float facX = pPage.bundleSize.X / img.PlainWidth; float fac = Math.Max(facX, facY); img.ScalePercent(fac * 100f); float yoffset = (img.ScaledHeight - pPage.bundleSize.Y) * -0.5f; float xoffset = (img.ScaledWidth - pPage.bundleSize.X) * -0.5f; img.SetAbsolutePosition(xoffset, yoffset); float width = -xoffset + ((pPage.type == Page.Type.Fullcover) ? pPage.bundleSize.X : pPage.bundleSize.X / 2f); Image imgCropped = cropImage(img, _writer, 0, 0, width, img.ScaledHeight); imgCropped.SetAbsolutePosition(xoffset, yoffset); canvas.AddImage(imgCropped); } } // draw right background if (pPage.backgroundRight != null) { canvas.Rectangle(pPage.bundleSize.X / 2, 0, pPage.bundleSize.X / 2, pPage.bundleSize.Y); #if DEBUG || _DEBUG canvas.SetColorFill(BaseColor.CYAN); canvas.SetColorFill(BaseColor.WHITE); #endif canvas.Fill(); string id = pPage.backgroundRight; System.Drawing.Image sysImg = DesignIdConverter.getImageFromID(id); if (sysImg == null) { Log.Error("Background image for id '" + id + "' was null."); #if DEBUG || _DEBUG canvas.SetColorFill(BaseColor.MAGENTA); #else canvas.SetColorFill(BaseColor.WHITE); #endif canvas.Fill(); canvas.Fill(); } else { Image img = sysImageToITextImage(sysImg); float facY = pPage.bundleSize.Y / img.PlainHeight; float facX = pPage.bundleSize.X / img.PlainWidth; float fac = Math.Max(facX, facY); img.ScalePercent(fac * 100f); float yoffset = (img.ScaledHeight - pPage.bundleSize.Y) * -0.5f; float xoffset = (img.ScaledWidth - pPage.bundleSize.X) * -0.5f; img.SetAbsolutePosition(xoffset, yoffset); Image imgCropped = cropImage(img, _writer, pPage.bundleSize.X / 2f, 0, img.ScaledWidth, img.ScaledHeight); imgCropped.SetAbsolutePosition(xoffset + pPage.bundleSize.X / 2, yoffset); canvas.AddImage(imgCropped); } } // draw all supported content areas stored in this page foreach (Area area in pPage.areas) { // calculate rect dimensions // TODO: de-duplicate? float pX = area.rect.X; float pY = pPage.bundleSize.Y - area.rect.Y - area.rect.Height; // handle rotation canvas.SaveState(); AffineTransform tf = new AffineTransform(); double angle = area.rotation * Math.PI / 180.0; tf.Rotate(-angle, pX + area.rect.Width / 2f, pY + area.rect.Height / 2f); // rotate around center ccw canvas.Transform(tf); if (area is ImageArea || area is ImageBackgroundArea) { // TODO: This is somewhat hacky - there is probably a better way to do this. if (area is ImageBackgroundArea) { ImageBackgroundArea bgArea = (ImageBackgroundArea)area; if (bgArea.type == ImageBackgroundArea.ImageBackgroundType.Right) { bgArea.rect.X += pPage.bundleSize.X / 2f + pPage.spineSize / 2f; } } ImageArea imgArea = (ImageArea)area; // if image path was not valid draw magenta outline and print error if (imgArea.path == "NULL") { #if DEBUG || _DEBUG // calculate rect dimensions Rectangle nullRect = new Rectangle(pX, pY, pX + imgArea.rect.Width, pY + imgArea.rect.Height); // configure border nullRect.Border = 1 | 2 | 4 | 8; nullRect.BorderColor = BaseColor.MAGENTA; nullRect.BorderWidth = 4.0f; // draw to document canvas.Rectangle(nullRect); Log.Error("Image path was null. Probably caused by an empty image area."); canvas.RestoreState(); #endif continue; } // load image file. System.Drawing.Image sysImg; try { sysImg = System.Drawing.Image.FromFile(imgArea.path); } catch (System.Exception e) { if (e is System.IO.FileNotFoundException) { Log.Error("Loading image failed. Image at '" + imgArea.path + "' not found."); } else { Log.Error("Loading image failed wit error: '" + e.Message + "'"); } canvas.RestoreState(); continue; } // fix exif orientation ExifRotate(sysImg); // calculate resizing factor, results in equal pixel density for all images. float scale = 1f / imgArea.scale * Config.ImgScale; // the higher this value, the lower pixel density is. 0.0f = original resolution scale = scale < 1.0f ? 1.0f : scale; // never scale image up System.Drawing.Size newSize = new System.Drawing.Size((int)(sysImg.Width / scale), (int)(sysImg.Height / scale)); // resize image sysImg = (System.Drawing.Image)(new System.Drawing.Bitmap(sysImg, newSize)); Image img = sysImageToITextImage(sysImg); // apply scale as defined in .mcf img.ScalePercent(imgArea.scale * 100.0f * scale); // calculate image position in pdf page float posX = imgArea.rect.X + imgArea.cutout.X; float posY = pPage.bundleSize.Y - imgArea.rect.Y - imgArea.rect.Height; // pdf origin is in lower left, mcf origin is in upper left // yaaaaa... whatever. This way everything fits float cropBottom = img.ScaledHeight - imgArea.rect.Height + imgArea.cutout.Y; // crop image to mcf specified rect Image cropped = cropImage(img, _writer, -imgArea.cutout.X, cropBottom, imgArea.rect.Width, imgArea.rect.Height); // move to mcf specified position cropped.SetAbsolutePosition(imgArea.rect.X, posY); string imgType = area is ImageBackgroundArea ? "ImageBackground" : "Image"; Log.Info("Rendering " + imgType + " (." + imgArea.path.Split(".").Last() + "): " + "original: " + sysImg.Width + "x" + sysImg.Height + "; " + "scaled: " + newSize.Width + "x" + newSize.Height + "; " + "cropped: " + (int)cropped.Width + "x" + (int)cropped.Height + "; " + "at: " + (int)cropped.AbsoluteX + ", " + (int)cropped.AbsoluteY); // draw the image canvas.AddImage(cropped); // draw image border if specified in .mcf if (imgArea.border) { // TODO mcf as an outside property that is currently not taken into account. // seems like all borders are 'outside' in photobook. // iTextSharp draws Borders centered (BorderWidth/2 pixels overlap image) // this should be corrected. // calc border rect Rectangle rect = new Rectangle(pX, pY, pX + imgArea.rect.Width, pY + imgArea.rect.Height); // convert .mcf's html style color hex code to Color, based on: https://stackoverflow.com/a/2109904 int argb = Int32.Parse(imgArea.borderColor.Replace("#", ""), System.Globalization.NumberStyles.HexNumber); System.Drawing.Color clr = System.Drawing.Color.FromArgb(argb); // configure border rect.Border = 1 | 2 | 4 | 8; rect.BorderColor = new BaseColor(clr); rect.BorderWidth = imgArea.borderWidth; // draw border canvas.Rectangle(rect); } } else if (area is TextArea) { TextArea textArea = (TextArea)area; // Render text background if not transparent if (!textArea.backgroundcolor.EndsWith("00")) { Log.Info("Rendering Text background: color=" + textArea.backgroundcolor); canvas.Rectangle(pX, pY, textArea.rect.Width, textArea.rect.Height); canvas.SetColorFill(argb2BaseColor(textArea.backgroundcolor)); canvas.Fill(); } // just in case something went wrong if (String.IsNullOrWhiteSpace(textArea.text)) { Log.Error("Text was empty."); canvas.RestoreState(); continue; } else { Log.Info("Rendering Text: font=" + textArea.font + "; size=" + textArea.fontsize + "; align=" + textArea.align + "; valign=" + textArea.valign); } // iTextSharp textbox ColumnText colText = new ColumnText(canvas); // calculate rect float llx = textArea.rect.X; float lly = pPage.bundleSize.Y - textArea.rect.Y - textArea.rect.Height; float urx = llx + textArea.rect.Width; float ury = lly + textArea.rect.Height; Rectangle textRect = new Rectangle(llx, lly, urx, ury); // apply rect to textbox colText.SetSimpleColumn(textRect); // The actual text object Paragraph par = new Paragraph(); // magic number that closely matches photobook // TODO there is probably more information in the .mcf's css part par.SetLeading(0, 1.3f); // apply corrent alignment if (textArea.align == "ALIGNHCENTER") { par.Alignment = Element.ALIGN_CENTER; } else if (textArea.align == "ALIGNLEFT") { par.Alignment = Element.ALIGN_LEFT; } else if (textArea.align == "ALIGNRIGHT") { par.Alignment = Element.ALIGN_RIGHT; } else if (textArea.align == "ALIGNJUSTIFY") { par.Alignment = Element.ALIGN_JUSTIFIED; } else { Log.Warning("Unhandled text align: '" + textArea.align + "'."); } // add text chunks foreach (TextElement elem in textArea.textElements) { int style = 0; style += elem.bold ? Font.BOLD : 0; style += elem.italic ? Font.ITALIC : 0; style += elem.underlined ? Font.UNDERLINE : 0; Font fnt = FontFactory.GetFont(elem.family, elem.size, style, argb2BaseColor(elem.color)); par.Add(new Chunk(elem.text + (elem.newline ? "\n" : " "), fnt)); } int valign = 0; if (textArea.valign == "ALIGNVCENTER") { valign = Element.ALIGN_MIDDLE; } else if (textArea.valign == "ALIGNVTOP") { valign = Element.ALIGN_TOP; } else if (textArea.valign == "ALIGNVBOTTOM") { valign = Element.ALIGN_BOTTOM; } else { Log.Warning("Unhandled text vertical align: '" + textArea.valign + "'."); } // v align needs a table... PdfPTable table = new PdfPTable(1); table.SetWidths(new int[] { 1 }); table.WidthPercentage = 100; table.AddCell(new PdfPCell(par) { HorizontalAlignment = par.Alignment, VerticalAlignment = valign, FixedHeight = textArea.rect.Height, Border = 0, }); // add paragraph to textbox colText.AddElement(table); // draw textbox colText.Go(); } // restore canvas transform before rotation canvas.RestoreState(); } // draw pagenumbers // TODO remove magic numbers, at least comment const float PAGE_NR_Y_OFFSET = -4.0f; const float PAGE_NR_X_OFFSET = 0.0f; float PAGE_NR_FONT_SIZE = Page.pageNoFontSize * 1.1f; float PAGE_NR_HEIGHT = PAGE_NR_FONT_SIZE + 12.0f; // add some extra space... this is needed. float PAGE_Y_POS = Page.pageNoMargin.Y + PAGE_NR_Y_OFFSET; // TODO de-duplicate all these conversions and move to helper method // convert .mcf's html style color hex code to Color, based on: https://stackoverflow.com/a/2109904 int argb_ = Int32.Parse(Page.pageNoColor.Replace("#", ""), System.Globalization.NumberStyles.HexNumber); System.Drawing.Color clr_ = System.Drawing.Color.FromArgb(argb_); // left Paragraph pageNoLeft = new Paragraph(pPage.pageNoLeft, FontFactory.GetFont(Page.pageNoFont, PAGE_NR_FONT_SIZE, new BaseColor(clr_))); pageNoLeft.Alignment = Element.ALIGN_LEFT + Element.ALIGN_BOTTOM; ColumnText leftNo = new ColumnText(_writer.DirectContent); Rectangle leftNoRect = new Rectangle(Page.pageNoMargin.X + PAGE_NR_X_OFFSET, PAGE_Y_POS, 500, PAGE_Y_POS + PAGE_NR_HEIGHT); leftNo.SetSimpleColumn(leftNoRect); leftNo.AddElement(pageNoLeft); leftNo.Go(); //leftNoRect.Border = 1 | 2 | 4 | 8; //leftNoRect.BorderColor = BaseColor.GREEN; //leftNoRect.BorderWidth = 1.0f; //_writer.DirectContent.Rectangle(leftNoRect); // right Paragraph pageNoRight = new Paragraph(pPage.pageNoRight, FontFactory.GetFont(Page.pageNoFont, PAGE_NR_FONT_SIZE, new BaseColor(clr_))); pageNoRight.Alignment = Element.ALIGN_RIGHT; ColumnText rightNo = new ColumnText(_writer.DirectContent); Rectangle rightNoRect = new Rectangle(pPage.bundleSize.X - Page.pageNoMargin.X - PAGE_NR_X_OFFSET - 500, PAGE_Y_POS, pPage.bundleSize.X - Page.pageNoMargin.X - PAGE_NR_X_OFFSET, PAGE_Y_POS + PAGE_NR_HEIGHT); rightNo.SetSimpleColumn(rightNoRect); rightNo.AddElement(pageNoRight); rightNo.Go(); //rightNoRect.Border = 1 | 2 | 4 | 8; //rightNoRect.BorderColor = BaseColor.YELLOW; //rightNoRect.BorderWidth = 1.0f; //_writer.DirectContent.Rectangle(rightNoRect); //Console.WriteLine("Page drawn: " + pPage.type.ToString() + " left: " + pPage.pageNoLeft + "; right: " + pPage.pageNoRight + "!"); }
public void ReadAll() { if (meta.ReadInt() != unchecked ((int)0x9AC6CDD7)) { throw new DocumentException("Not a placeable windows metafile"); } meta.ReadWord(); left = meta.ReadShort(); top = meta.ReadShort(); right = meta.ReadShort(); bottom = meta.ReadShort(); inch = meta.ReadWord(); state.ScalingX = (float)(right - left) / (float)inch * 72f; state.ScalingY = (float)(bottom - top) / (float)inch * 72f; state.OffsetWx = left; state.OffsetWy = top; state.ExtentWx = right - left; state.ExtentWy = bottom - top; meta.ReadInt(); meta.ReadWord(); meta.Skip(18); int tsize; int function; cb.SetLineCap(1); cb.SetLineJoin(1); for (;;) { int lenMarker = meta.Length; tsize = meta.ReadInt(); if (tsize < 3) { break; } function = meta.ReadWord(); switch (function) { case 0: break; case META_CREATEPALETTE: case META_CREATEREGION: case META_DIBCREATEPATTERNBRUSH: state.AddMetaObject(new MetaObject()); break; case META_CREATEPENINDIRECT: { MetaPen pen = new MetaPen(); pen.Init(meta); state.AddMetaObject(pen); break; } case META_CREATEBRUSHINDIRECT: { MetaBrush brush = new MetaBrush(); brush.Init(meta); state.AddMetaObject(brush); break; } case META_CREATEFONTINDIRECT: { MetaFont font = new MetaFont(); font.Init(meta); state.AddMetaObject(font); break; } case META_SELECTOBJECT: { int idx = meta.ReadWord(); state.SelectMetaObject(idx, cb); break; } case META_DELETEOBJECT: { int idx = meta.ReadWord(); state.DeleteMetaObject(idx); break; } case META_SAVEDC: state.SaveState(cb); break; case META_RESTOREDC: { int idx = meta.ReadShort(); state.RestoreState(idx, cb); break; } case META_SETWINDOWORG: state.OffsetWy = meta.ReadShort(); state.OffsetWx = meta.ReadShort(); break; case META_SETWINDOWEXT: state.ExtentWy = meta.ReadShort(); state.ExtentWx = meta.ReadShort(); break; case META_MOVETO: { int y = meta.ReadShort(); System.Drawing.Point p = new System.Drawing.Point(meta.ReadShort(), y); state.CurrentPoint = p; break; } case META_LINETO: { int y = meta.ReadShort(); int x = meta.ReadShort(); System.Drawing.Point p = state.CurrentPoint; cb.MoveTo(state.TransformX(p.X), state.TransformY(p.Y)); cb.LineTo(state.TransformX(x), state.TransformY(y)); cb.Stroke(); state.CurrentPoint = new System.Drawing.Point(x, y); break; } case META_POLYLINE: { state.LineJoinPolygon = cb; int len = meta.ReadWord(); int x = meta.ReadShort(); int y = meta.ReadShort(); cb.MoveTo(state.TransformX(x), state.TransformY(y)); for (int k = 1; k < len; ++k) { x = meta.ReadShort(); y = meta.ReadShort(); cb.LineTo(state.TransformX(x), state.TransformY(y)); } cb.Stroke(); break; } case META_POLYGON: { if (IsNullStrokeFill(false)) { break; } int len = meta.ReadWord(); int sx = meta.ReadShort(); int sy = meta.ReadShort(); cb.MoveTo(state.TransformX(sx), state.TransformY(sy)); for (int k = 1; k < len; ++k) { int x = meta.ReadShort(); int y = meta.ReadShort(); cb.LineTo(state.TransformX(x), state.TransformY(y)); } cb.LineTo(state.TransformX(sx), state.TransformY(sy)); StrokeAndFill(); break; } case META_POLYPOLYGON: { if (IsNullStrokeFill(false)) { break; } int numPoly = meta.ReadWord(); int[] lens = new int[numPoly]; for (int k = 0; k < lens.Length; ++k) { lens[k] = meta.ReadWord(); } for (int j = 0; j < lens.Length; ++j) { int len = lens[j]; int sx = meta.ReadShort(); int sy = meta.ReadShort(); cb.MoveTo(state.TransformX(sx), state.TransformY(sy)); for (int k = 1; k < len; ++k) { int x = meta.ReadShort(); int y = meta.ReadShort(); cb.LineTo(state.TransformX(x), state.TransformY(y)); } cb.LineTo(state.TransformX(sx), state.TransformY(sy)); } StrokeAndFill(); break; } case META_ELLIPSE: { if (IsNullStrokeFill(state.LineNeutral)) { break; } int b = meta.ReadShort(); int r = meta.ReadShort(); int t = meta.ReadShort(); int l = meta.ReadShort(); cb.Arc(state.TransformX(l), state.TransformY(b), state.TransformX(r), state.TransformY(t), 0, 360); StrokeAndFill(); break; } case META_ARC: { if (IsNullStrokeFill(state.LineNeutral)) { break; } float yend = state.TransformY(meta.ReadShort()); float xend = state.TransformX(meta.ReadShort()); float ystart = state.TransformY(meta.ReadShort()); float xstart = state.TransformX(meta.ReadShort()); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); float cx = (r + l) / 2; float cy = (t + b) / 2; float arc1 = GetArc(cx, cy, xstart, ystart); float arc2 = GetArc(cx, cy, xend, yend); arc2 -= arc1; if (arc2 <= 0) { arc2 += 360; } cb.Arc(l, b, r, t, arc1, arc2); cb.Stroke(); break; } case META_PIE: { if (IsNullStrokeFill(state.LineNeutral)) { break; } float yend = state.TransformY(meta.ReadShort()); float xend = state.TransformX(meta.ReadShort()); float ystart = state.TransformY(meta.ReadShort()); float xstart = state.TransformX(meta.ReadShort()); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); float cx = (r + l) / 2; float cy = (t + b) / 2; float arc1 = GetArc(cx, cy, xstart, ystart); float arc2 = GetArc(cx, cy, xend, yend); arc2 -= arc1; if (arc2 <= 0) { arc2 += 360; } ArrayList ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2); if (ar.Count == 0) { break; } float[] pt = (float [])ar[0]; cb.MoveTo(cx, cy); cb.LineTo(pt[0], pt[1]); for (int k = 0; k < ar.Count; ++k) { pt = (float [])ar[k]; cb.CurveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]); } cb.LineTo(cx, cy); StrokeAndFill(); break; } case META_CHORD: { if (IsNullStrokeFill(state.LineNeutral)) { break; } float yend = state.TransformY(meta.ReadShort()); float xend = state.TransformX(meta.ReadShort()); float ystart = state.TransformY(meta.ReadShort()); float xstart = state.TransformX(meta.ReadShort()); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); float cx = (r + l) / 2; float cy = (t + b) / 2; float arc1 = GetArc(cx, cy, xstart, ystart); float arc2 = GetArc(cx, cy, xend, yend); arc2 -= arc1; if (arc2 <= 0) { arc2 += 360; } ArrayList ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2); if (ar.Count == 0) { break; } float[] pt = (float [])ar[0]; cx = pt[0]; cy = pt[1]; cb.MoveTo(cx, cy); for (int k = 0; k < ar.Count; ++k) { pt = (float [])ar[k]; cb.CurveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]); } cb.LineTo(cx, cy); StrokeAndFill(); break; } case META_RECTANGLE: { if (IsNullStrokeFill(true)) { break; } float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); cb.Rectangle(l, b, r - l, t - b); StrokeAndFill(); break; } case META_ROUNDRECT: { if (IsNullStrokeFill(true)) { break; } float h = state.TransformY(0) - state.TransformY(meta.ReadShort()); float w = state.TransformX(meta.ReadShort()) - state.TransformX(0); float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); cb.RoundRectangle(l, b, r - l, t - b, (h + w) / 4); StrokeAndFill(); break; } case META_INTERSECTCLIPRECT: { float b = state.TransformY(meta.ReadShort()); float r = state.TransformX(meta.ReadShort()); float t = state.TransformY(meta.ReadShort()); float l = state.TransformX(meta.ReadShort()); cb.Rectangle(l, b, r - l, t - b); cb.EoClip(); cb.NewPath(); break; } case META_EXTTEXTOUT: { int y = meta.ReadShort(); int x = meta.ReadShort(); int count = meta.ReadWord(); int flag = meta.ReadWord(); int x1 = 0; int y1 = 0; int x2 = 0; int y2 = 0; if ((flag & (MetaFont.ETO_CLIPPED | MetaFont.ETO_OPAQUE)) != 0) { x1 = meta.ReadShort(); y1 = meta.ReadShort(); x2 = meta.ReadShort(); y2 = meta.ReadShort(); } byte[] text = new byte[count]; int k; for (k = 0; k < count; ++k) { byte c = (byte)meta.ReadByte(); if (c == 0) { break; } text[k] = c; } string s; try { s = System.Text.Encoding.GetEncoding(1252).GetString(text, 0, k); } catch { s = System.Text.ASCIIEncoding.ASCII.GetString(text, 0, k); } OutputText(x, y, flag, x1, y1, x2, y2, s); break; } case META_TEXTOUT: { int count = meta.ReadWord(); byte[] text = new byte[count]; int k; for (k = 0; k < count; ++k) { byte c = (byte)meta.ReadByte(); if (c == 0) { break; } text[k] = c; } string s; try { s = System.Text.Encoding.GetEncoding(1252).GetString(text, 0, k); } catch { s = System.Text.ASCIIEncoding.ASCII.GetString(text, 0, k); } count = (count + 1) & 0xfffe; meta.Skip(count - k); int y = meta.ReadShort(); int x = meta.ReadShort(); OutputText(x, y, 0, 0, 0, 0, 0, s); break; } case META_SETBKCOLOR: state.CurrentBackgroundColor = meta.ReadColor(); break; case META_SETTEXTCOLOR: state.CurrentTextColor = meta.ReadColor(); break; case META_SETTEXTALIGN: state.TextAlign = meta.ReadWord(); break; case META_SETBKMODE: state.BackgroundMode = meta.ReadWord(); break; case META_SETPOLYFILLMODE: state.PolyFillMode = meta.ReadWord(); break; case META_SETPIXEL: { Color color = meta.ReadColor(); int y = meta.ReadShort(); int x = meta.ReadShort(); cb.SaveState(); cb.SetColorFill(color); cb.Rectangle(state.TransformX(x), state.TransformY(y), .2f, .2f); cb.Fill(); cb.RestoreState(); break; } case META_DIBSTRETCHBLT: case META_STRETCHDIB: { int rop = meta.ReadInt(); if (function == META_STRETCHDIB) { /*int usage = */ meta.ReadWord(); } int srcHeight = meta.ReadShort(); int srcWidth = meta.ReadShort(); int ySrc = meta.ReadShort(); int xSrc = meta.ReadShort(); float destHeight = state.TransformY(meta.ReadShort()) - state.TransformY(0); float destWidth = state.TransformX(meta.ReadShort()) - state.TransformX(0); float yDest = state.TransformY(meta.ReadShort()); float xDest = state.TransformX(meta.ReadShort()); byte[] b = new byte[(tsize * 2) - (meta.Length - lenMarker)]; for (int k = 0; k < b.Length; ++k) { b[k] = (byte)meta.ReadByte(); } try { MemoryStream inb = new MemoryStream(b); Image bmp = BmpImage.GetImage(inb, true, b.Length); cb.SaveState(); cb.Rectangle(xDest, yDest, destWidth, destHeight); cb.Clip(); cb.NewPath(); bmp.ScaleAbsolute(destWidth * bmp.Width / srcWidth, -destHeight * bmp.Height / srcHeight); bmp.SetAbsolutePosition(xDest - destWidth * xSrc / srcWidth, yDest + destHeight * ySrc / srcHeight - bmp.ScaledHeight); cb.AddImage(bmp); cb.RestoreState(); } catch { // empty on purpose } break; } } meta.Skip((tsize * 2) - (meta.Length - lenMarker)); } state.Cleanup(cb); }
/* Draw one note, do = 1. * content: Drawing content container. * left: Beginning position. * up: Beginning position. * number: Tone. * length: Length of the note, currently support 1, 0.75, 0.5, 0.25. */ private void DrawOneScore(PdfContentByte content, float left, float up, double number, double length = 1) { // TODO(allenxie): Deal with flag == false. up = PageSize.A4.Height - up; float position = up - 5 * lineSpace + ((float)number - 1) * lineSpace / 2; // Circle content.SetColorFill(BaseColor.BLACK); // content.Circle(left, position, scoreRadius); content.Ellipse(left - 4, position - 3, left + 4, position + 3); content.Fill(); // Vertical line (0.5 is for good-looking) if (number < 8) { content.MoveTo(left + scoreRadius + 0.5, position); content.LineTo(left + scoreRadius + 0.5, position + 3.5 * lineSpace); content.Stroke(); if (length == 0.5 || length == 0.75) { double left_start = left + scoreRadius + 0.5; double up_start = position + 3.5 * lineSpace - 0.5; content.MoveTo(left_start, up_start); content.CurveTo(left_start + 1, up_start - 4, left_start + 7, up_start - 7, left_start + 4, up_start - 12); content.Stroke(); if (length == 0.75) { double dot_position = (number % 2 == 0) ? position : position + 0.5 * lineSpace; content.Circle(left_start + 3, dot_position, 1); content.Fill(); } } if (length == 0.25) { double left_start = left + scoreRadius + 0.5; double up_start = position + 3.5 * lineSpace - 0.5; content.MoveTo(left_start, up_start); content.CurveTo(left_start + 1, up_start - 3, left_start + 6, up_start - 6, left_start + 3, up_start - 9); content.Stroke(); up_start = up_start - 4; content.MoveTo(left_start, up_start); content.CurveTo(left_start + 1, up_start - 3, left_start + 6, up_start - 6, left_start + 3, up_start - 9); content.Stroke(); } } else { content.MoveTo(left - scoreRadius - 0.5, position); content.LineTo(left - scoreRadius - 0.5, position - 3.5 * lineSpace); content.Stroke(); if (length == 0.5 || length == 0.75) { double left_start = left - scoreRadius - 0.5; double up_start = position - 3.5 * lineSpace + 0.5; content.MoveTo(left_start, up_start); content.CurveTo(left_start + 1, up_start + 4, left_start + 7, up_start + 7, left_start + 4, up_start + 12); content.Stroke(); if (length == 0.75) { double dot_position = (number % 2 == 0) ? position : position + 0.5 * lineSpace; content.Circle(left_start + 8, dot_position, 1); content.Fill(); } } if (length == 0.25) { double left_start = left - scoreRadius - 0.5; double up_start = position - 3.5 * lineSpace + 0.5; content.MoveTo(left_start, up_start); content.CurveTo(left_start + 1, up_start + 3, left_start + 6, up_start + 6, left_start + 3, up_start + 9); content.Stroke(); up_start = up_start + 4; content.MoveTo(left_start, up_start); content.CurveTo(left_start + 1, up_start + 3, left_start + 6, up_start + 6, left_start + 3, up_start + 9); content.Stroke(); } } // If need addition lateral line if (number < 2 && ((int)number % 2 == 0)) { content.MoveTo(left - scoreRadius * 2, position + scoreRadius); content.LineTo(left + scoreRadius * 2, position + scoreRadius); content.Stroke(); } else if (number < 2 && ((int)number % 2 != 0)) { content.MoveTo(left - scoreRadius * 2, position); content.LineTo(left + scoreRadius * 2, position); content.Stroke(); } else if (number > 12 && ((int)number % 2 == 0)) { content.MoveTo(left - scoreRadius * 2, position - scoreRadius); content.LineTo(left + scoreRadius * 2, position - scoreRadius); content.Stroke(); } else if (number > 12 && ((int)number % 2 != 0)) { content.MoveTo(left - scoreRadius * 2, position); content.LineTo(left + scoreRadius * 2, position); content.Stroke(); } }
/** 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; }
private void CreatePDF(object sender, DoWorkEventArgs e) { int progressValue = 0; string filename; PdfWriter pdfWriter = null; Bitmap bmpCrop; Bitmap[] bitmaps; RectangleF[] srcRects; BackgroundWorker worker = sender as BackgroundWorker; // Get the bitmaps from the slots panel bitmaps = new Bitmap[m_cropperForm.m_slotsPanel.Bitmaps.Length]; for (int i = 0; i < bitmaps.Length; i++) { bitmaps[i] = new Bitmap(m_cropperForm.m_slotsPanel.Bitmaps[i]); } // Get the rectangles from the slots panel srcRects = new RectangleF[m_cropperForm.m_slotsPanel.SourceRectangles.Length]; for (int i = 0; i < bitmaps.Length; i++) { srcRects[i] = new RectangleF( m_cropperForm.m_slotsPanel.SourceRectangles[i].X, m_cropperForm.m_slotsPanel.SourceRectangles[i].Y, m_cropperForm.m_slotsPanel.SourceRectangles[i].Width, m_cropperForm.m_slotsPanel.SourceRectangles[i].Height); } // Get the filename filename = (string)e.Argument; // Save all cropped images try { for (int i = 0; i < m_cropperForm.m_slotsPanel.SlotCount; i++) { bmpCrop = bitmaps[i].Clone(srcRects[i], bitmaps[i].PixelFormat); bmpCrop.Save(Application.StartupPath + "//Data//PDF//Domino_PDF//Slot" + (i + 1) + ".jpg"); // Calculate the progress bar value progressValue = (int)(((i + 1) / 7.0f) * 33); worker.ReportProgress(progressValue); } // If the pdf creation is cancelled if (worker.CancellationPending) { e.Cancel = true; return; } } catch (Exception err) { MessageBox.Show(err.Message, m_cropperForm.m_langDictionary["Create PDF"], MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.Cancel = true; return; } // Create the PDF document try { // Initialize the PDF document m_document = new iTextSharp.text.Document(m_pageSize); m_document.SetMargins(0f, 0f, 0f, 0f); // Create the pdf writer pdfWriter = PdfWriter.GetInstance(m_document, new FileStream(filename, FileMode.Create)); // Open the pdf document m_document.Open(); // Draw the corner dots m_cb = pdfWriter.DirectContent; m_cb.SetCMYKColorFill(0, 0, 0, 255); // BOTTOM LEFT float radius = 3.8f / 2.0f; m_cb.Circle(18f + radius, 165.1f + radius, radius); m_cb.Fill(); // TOP LEFT m_cb.Circle(16.8f + radius, 622.3f + radius, radius); m_cb.Fill(); // TOP RIGHT m_cb.Circle(572.2f + radius, 678f + radius, radius); m_cb.Fill(); // BOTTOM RIGHT m_cb.Circle(574.6f + radius, 109.4f + radius, radius); m_cb.Fill(); // Fill the images array m_images = new iTextSharp.text.Image[m_cropperForm.m_slotsPanel.SlotCount]; for (int i = 0; i < m_images.Length; i++) { // If the pdf creation is cancelled if (worker.CancellationPending) { e.Cancel = true; return; } m_images[i] = iTextSharp.text.Image.GetInstance(Application.StartupPath + "//Data//PDF//Domino_PDF//Slot" + (i + 1) + ".jpg"); float prec = imgWidth / m_images[i].Width; m_images[i].ScalePercent(prec * 100); m_images[i].RotationDegrees = 90; m_images[i].Rotate(); // Calculate the progress bar value progressValue = 33 + (int)(((i + 1) / (float)m_images.Length) * 12); worker.ReportProgress(progressValue); } // Draw the slots to te pdf for (int i = 0; i < m_cropperForm.m_slotsPanel.SlotCount; i++) { // If the pdf creation is cancelled if (worker.CancellationPending) { e.Cancel = true; return; } InvokeFunction("Slot" + (i + 1)); // Calculate the progress bar value progressValue += 3; worker.ReportProgress(progressValue); } // Tiles 1-20 Lines for (int i = 0; i < 20; i++) { // If the pdf creation is cancelled if (worker.CancellationPending) { e.Cancel = true; return; } m_cb.Rectangle( vertTilesMarginLeft + (i % 4) * (imgHeight + vertTilesHorizGap), vertTilesMarginBottom - ((2 * (i / 4) + 1) * imgWidth) - ((i / 4) * vertTilesVertGap) - (m_lineWidth / 2.0f), imgHeight + 0.5f, m_lineWidth); m_cb.Fill(); // Calculate the progress bar value progressValue = 66 + (int)(((i + 1) / 20.0f) * 12); worker.ReportProgress(progressValue); } // Tiles 20-28 Lines for (int i = 0; i < 8; i++) { // If the pdf creation is cancelled if (worker.CancellationPending) { e.Cancel = true; return; } m_cb.Rectangle( horizTilesMarginLeft + imgWidth - (m_lineWidth / 2.0f), horizTilesMarginBottom - ((i + 1) * imgHeight) - (i * horizTilesVertGap), m_lineWidth, imgHeight + 0.5f); m_cb.Fill(); // Calculate the progress bar value progressValue = 78 + (int)(((i + 1) / 8.0f) * 12); worker.ReportProgress(progressValue); } } catch (iTextSharp.text.DocumentException err) { MessageBox.Show(err.Message, m_cropperForm.m_langDictionary["Create PDF"], MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.Cancel = true; return; } catch (Exception err) { MessageBox.Show(err.Message, m_cropperForm.m_langDictionary["Create PDF"], MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.Cancel = true; return; } finally { // Clean up m_document.Close(); m_document = null; } // Delete all cropped images try { for (int i = 0; i < m_cropperForm.m_slotsPanel.SlotCount; i++) { string filePath = Application.StartupPath + "//Data//PDF//Domino_PDF//Slot" + (i + 1) + ".jpg"; if (File.Exists(filePath)) { File.Delete(filePath); } // Calculate the progress bar value progressValue = 90 + (int)(((i + 1) / 7.0f) * 10); worker.ReportProgress(progressValue); } // If the pdf creation is cancelled if (worker.CancellationPending) { e.Cancel = true; return; } } catch (Exception err) { MessageBox.Show(err.Message, m_cropperForm.m_langDictionary["Create PDF"], MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.Cancel = true; return; } }
virtual public void TableLayout(PdfPTable table, float[][] width, float[] height, int headerRows, int rowStart, PdfContentByte[] canvas) { float left = styleValues.BorderWidthLeft; float right = styleValues.BorderWidthRight; float top = styleValues.BorderWidthTop; float bottom = styleValues.BorderWidthBottom; float[] widths = width[0]; float effectivePadding = left / 2; float x1 = widths[0] - effectivePadding; effectivePadding = right / 2; float x2 = widths[widths.Length - 1] + effectivePadding; effectivePadding = top / 2; float y1 = height[0] + effectivePadding; effectivePadding = bottom / 2 + styleValues.VerBorderSpacing; float y2 = height[height.Length - 1] - effectivePadding; PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS]; BaseColor color = styleValues.Background; if (color != null) { cb.SetColorFill(color); cb.Rectangle(x1, y1, x2 - x1, y2 - y1); cb.Fill(); } cb = canvas[PdfPTable.LINECANVAS]; if (left != 0) { color = styleValues.BorderColorLeft; if (color == null) { color = BaseColor.BLACK; } cb.SetLineWidth(left); cb.SetColorStroke(color); cb.MoveTo(x1, y1); // start leftUpperCorner cb.LineTo(x1, y2); // left cb.Stroke(); } if (bottom != 0) { color = styleValues.BorderColorBottom; if (color == null) { color = BaseColor.BLACK; } cb.SetLineWidth(bottom); cb.SetColorStroke(color); cb.MoveTo(x1, y2); // left cb.LineTo(x2, y2); // bottom cb.Stroke(); } if (right != 0) { color = styleValues.BorderColorRight; if (color == null) { color = BaseColor.BLACK; } cb.SetLineWidth(right); cb.SetColorStroke(color); cb.MoveTo(x2, y2); // bottom cb.LineTo(x2, y1); // right cb.Stroke(); } if (top != 0) { color = styleValues.BorderColorTop; if (color == null) { color = BaseColor.BLACK; } cb.SetLineWidth(top); cb.SetColorStroke(color); cb.MoveTo(x2, y1); // right cb.LineTo(x1, y1); // top cb.Stroke(); } cb.ResetRGBColorStroke(); }
/** Places the barcode in a <CODE>PdfContentByte</CODE>. The * barcode is always placed at coodinates (0, 0). Use the * translation matrix to move it elsewhere.<p> * The bars and text are written in the following colors:<p> * <P><TABLE BORDER=1> * <TR> * <TH><P><CODE>barColor</CODE></TH> * <TH><P><CODE>textColor</CODE></TH> * <TH><P>Result</TH> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with current fill color</TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>null</CODE></TD> * <TD><P>bars and text painted with <CODE>barColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>null</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD> * </TR> * <TR> * <TD><P><CODE>barColor</CODE></TD> * <TD><P><CODE>textColor</CODE></TD> * <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD> * </TR> * </TABLE> * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed * @param barColor the color of the bars. It can be <CODE>null</CODE> * @param textColor the color of the text. It can be <CODE>null</CODE> * @return the dimensions the barcode occupies */ public override Rectangle PlaceBarcode(PdfContentByte cb, Color barColor, Color textColor) { string fullCode; if (codeType == CODE128_RAW) { int idx = code.IndexOf('\uffff'); if (idx < 0) fullCode = ""; else fullCode = code.Substring(idx + 1); } else if (codeType == CODE128_UCC) fullCode = GetHumanReadableUCCEAN(code); else fullCode = RemoveFNC1(code); float fontX = 0; if (font != null) { fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size); } string bCode; if (codeType == CODE128_RAW) { int idx = code.IndexOf('\uffff'); if (idx >= 0) bCode = code.Substring(0, idx); else bCode = code; } else { bCode = GetRawText(code, codeType == CODE128_UCC); } int len = bCode.Length; float fullWidth = (len + 2) * 11 * x + 2 * x; float barStartX = 0; float textStartX = 0; switch (textAlignment) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: if (fontX > fullWidth) barStartX = fontX - fullWidth; else textStartX = fullWidth - fontX; break; default: if (fontX > fullWidth) barStartX = (fontX - fullWidth) / 2; else textStartX = (fullWidth - fontX) / 2; break; } float barStartY = 0; float textStartY = 0; if (font != null) { if (baseline <= 0) textStartY = barHeight - baseline; else { textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size); barStartY = textStartY + baseline; } } byte[] bars = GetBarsCode128Raw(bCode); bool print = true; if (barColor != null) cb.SetColorFill(barColor); for (int k = 0; k < bars.Length; ++k) { float w = bars[k] * x; if (print) cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight); print = !print; barStartX += w; } cb.Fill(); if (font != null) { if (textColor != null) cb.SetColorFill(textColor); cb.BeginText(); cb.SetFontAndSize(font, size); cb.SetTextMatrix(textStartX, textStartY); cb.ShowText(fullCode); cb.EndText(); } return this.BarcodeSize; }
public static MemoryStream AdicionarTarjaPdf(Stream pdf, string texto1, string texto2, BaseColor corFundo, BaseColor corTexto) { MemoryStream ms = new MemoryStream(); PdfImportedPage page; PdfReader reader = new PdfReader(pdf); Document doc = new Document(reader.GetPageSizeWithRotation(1)); PdfContentByte cb = null; PdfWriter wrt = PdfWriter.GetInstance(doc, ms); wrt.PageEvent = null; doc.Open(); #region Páginas do Pdf for (int i = 1; i <= reader.NumberOfPages; i++) { doc.SetPageSize(reader.GetPageSizeWithRotation(i)); doc.NewPage(); cb = wrt.DirectContentUnder; cb.SaveState(); cb.SetColorFill(corFundo); cb.Rectangle(doc.PageSize.Right - 22, 0, 22, doc.PageSize.Height); cb.Fill(); cb.RestoreState(); cb.SaveState(); cb.SetColorFill(corTexto); cb.BeginText(); cb.SetFontAndSize(arial16.BaseFont, 16); cb.ShowTextAligned(Element.ALIGN_LEFT, texto1, doc.PageSize.Right - 8, 10, 90); cb.ShowTextAligned(Element.ALIGN_RIGHT, texto2, doc.PageSize.Right - 8, doc.PageSize.Height - 10, 90); cb.EndText(); cb.RestoreState(); cb.SaveState(); cb.ResetGrayFill(); cb.RestoreState(); cb.SaveState(); page = wrt.GetImportedPage(reader, i); if (doc.PageSize.Rotation == 0) { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } if (doc.PageSize.Rotation == 90) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, doc.PageSize.Height); } if (doc.PageSize.Rotation == 180) { cb.AddTemplate(page, -1f, 0, 0, -1f, doc.PageSize.Width, doc.PageSize.Height); } if (doc.PageSize.Rotation == 270) { cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, doc.PageSize.Width, 0); } cb.RestoreState(); } #endregion doc.Close(); MemoryStream msOut = new MemoryStream(ms.ToArray()); ms.Close(); ms.Dispose(); return(msOut); }
/** * @see com.itextpdf.text.pdf.PdfPCellEvent#cellLayout(com.itextpdf.text.pdf.PdfPCell, * com.itextpdf.text.Rectangle, com.itextpdf.text.pdf.PdfContentByte[]) */ public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { float effectivePadding = styleValues.BorderWidthLeft / 2 + styleValues.HorBorderSpacing; float x1 = position.Left + effectivePadding; if (styleValues.IsLastInRow) { effectivePadding = styleValues.BorderWidthRight / 2 + styleValues.HorBorderSpacing; } else { effectivePadding = styleValues.BorderWidthRight / 2; } float x2 = position.Right - effectivePadding; effectivePadding = styleValues.BorderWidthTop / 2 + styleValues.VerBorderSpacing; float y1 = position.Top - effectivePadding; effectivePadding = styleValues.BorderWidthBottom / 2; float y2 = position.Bottom + effectivePadding; PdfContentByte cb = canvases[PdfPTable.LINECANVAS]; BaseColor color = styleValues.Background; if (color != null) { cb.SetColorStroke(color); cb.SetColorFill(color); cb.Rectangle(x1, y1, x2 - x1, y2 - y1); cb.Fill(); } BaseColor borderColor = styleValues.BorderColorLeft; float width = styleValues.BorderWidthLeft; if (borderColor != null && width != 0) { cb.SetLineWidth(width); cb.SetColorStroke(borderColor); cb.MoveTo(x1, y1); // start leftUpperCorner cb.LineTo(x1, y2); // left cb.Stroke(); } borderColor = styleValues.BorderColorBottom; width = styleValues.BorderWidthBottom; if (borderColor != null && width != 0) { cb.SetLineWidth(width); cb.SetColorStroke(borderColor); cb.MoveTo(x1, y2); // left cb.LineTo(x2, y2); // bottom cb.Stroke(); } borderColor = styleValues.BorderColorRight; width = styleValues.BorderWidthRight; if (borderColor != null && width != 0) { cb.SetLineWidth(width); cb.SetColorStroke(borderColor); cb.MoveTo(x2, y2); // bottom cb.LineTo(x2, y1); // right cb.Stroke(); } borderColor = styleValues.BorderColorTop; width = styleValues.BorderWidthTop; if (borderColor != null && width != 0) { cb.SetLineWidth(width); cb.SetColorStroke(borderColor); cb.MoveTo(x2, y1); // right cb.LineTo(x1, y1); // top cb.Stroke(); } cb.ResetRGBColorStroke(); }
public static void DrawRectangle(PdfContentByte canvas, Rectangle rectangle, BaseColor baseColor) { canvas.SetColorFill(baseColor); canvas.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height); canvas.Fill(); }
public void Draw(PdfContentByte cb, int y) { int yPosition = y; int currentHeight = CalculateHeight(); int HEIGHT = currentHeight >= MINIMUMHEIGHT ? currentHeight : MINIMUMHEIGHT; int TOP = yPosition + HEIGHT; int BOTTOM = yPosition; int SPECIFICATIONHEIGHT = CalculateSpecificationElementHeight(); BaseFont f_cb = BaseFont.CreateFont("c:\\windows\\fonts\\calibrib.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); //Background of element cb.SetColorFill(new BaseColor(245, 245, 245)); cb.Rectangle(0, BOTTOM, WINDOWWIDTH, HEIGHT); cb.Fill(); //Top bar background cb.SetColorFill(new BaseColor(22, 137, 206)); cb.Rectangle(0, TOP - TOPBARHEIGHT, WINDOWWIDTH, TOPBARHEIGHT); cb.Fill(); //Top bar text cb.BeginText(); cb.SetFontAndSize(f_cb, 20); cb.SetColorFill(BaseColor.WHITE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, headerText, 20, TOP - 26, 0); cb.EndText(); //Shadow line under top bar cb.SetColorStroke(new BaseColor(222, 222, 222)); cb.SetLineWidth(2); cb.MoveTo(0, TOP - TOPBARHEIGHT - 1); cb.LineTo(WINDOWWIDTH, TOP - TOPBARHEIGHT - 1); cb.ClosePathFillStroke(); //Image of product Image img = Image.GetInstance("mokgroen.jpg"); img.SetAbsolutePosition(MARGIN, TOP - TOPBARHEIGHT - 200 + MARGIN); img.ScaleAbsolute(200 - MARGIN - MARGIN, 200 - MARGIN - MARGIN); cb.AddImage(img); //Shadow line under image cb.SetColorStroke(new BaseColor(222, 222, 222)); cb.SetLineWidth(2); cb.MoveTo(MARGIN, TOP - TOPBARHEIGHT - 200 + MARGIN); cb.LineTo(200 - MARGIN, TOP - TOPBARHEIGHT - 200 + MARGIN); cb.ClosePathFillStroke(); //Background of summary element cb.SetColorFill(new BaseColor(255, 255, 255)); cb.Rectangle(200, TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT, WINDOWWIDTH - 200 - MARGIN, SUMMARYHEIGHT); cb.Fill(); //Header text for summary cb.BeginText(); cb.SetFontAndSize(f_cb, 12); cb.SetColorFill(new BaseColor(22, 137, 206)); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Description", 210, TOP - TOPBARHEIGHT - MARGIN - 15, 0); //Summary text inside element cb.SetFontAndSize(f_cb, 12); cb.SetColorFill(new BaseColor(120, 120, 120)); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, summaryText, 210, TOP - TOPBARHEIGHT - MARGIN - 35, 0); cb.EndText(); //Shadow line under summary cb.SetColorStroke(new BaseColor(222, 222, 222)); cb.SetLineWidth(2); cb.MoveTo(200, TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT - 1); cb.LineTo(200 + WINDOWWIDTH - 200 - MARGIN, TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT - 1); cb.ClosePathFillStroke(); if (specifications.Count > 0) { //Background of specifications cb.SetColorFill(new BaseColor(255, 255, 255)); cb.Rectangle(200, TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT - MARGIN - SPECIFICATIONHEIGHT, WINDOWWIDTH - 200 - MARGIN, SPECIFICATIONHEIGHT); cb.Fill(); //Header text for specifications cb.BeginText(); cb.SetFontAndSize(f_cb, 12); cb.SetColorFill(new BaseColor(22, 137, 206)); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Specifications", 210, TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT - MARGIN - 15, 0); //Summary text inside specifications cb.SetFontAndSize(f_cb, 12); cb.SetColorFill(new BaseColor(120, 120, 120)); for (int i = 0; i < specifications.Count; i++) { string[] specValuePairs = specifications[i]; int textYPos = TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT - MARGIN - 25 - 15 - (25 * i); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, specValuePairs[0], 210, textYPos, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, specValuePairs[1], 320, textYPos, 0); } cb.EndText(); //Shadow line under specifications cb.SetColorStroke(new BaseColor(222, 222, 222)); cb.SetLineWidth(2); cb.MoveTo(200, TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT - MARGIN - SPECIFICATIONHEIGHT - 1); cb.LineTo(200 + WINDOWWIDTH - 200 - MARGIN, TOP - TOPBARHEIGHT - MARGIN - SUMMARYHEIGHT - MARGIN - SPECIFICATIONHEIGHT - 1); cb.ClosePathFillStroke(); } }
/** 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; }
/** * Writes a text line to the document. It takes care of all the attributes. * <P> * Before entering the line position must have been established and the * <CODE>text</CODE> argument must be in text object scope (<CODE>beginText()</CODE>). * @param line the line to be written * @param text the <CODE>PdfContentByte</CODE> where the text will be written to * @param graphics the <CODE>PdfContentByte</CODE> where the graphics will be written to * @param currentValues the current font and extra spacing values * @param ratio * @throws DocumentException on error */ internal void WriteLineToContent(PdfLine line, PdfContentByte text, PdfContentByte graphics, Object[] currentValues, float ratio) { PdfFont currentFont = (PdfFont)(currentValues[0]); float lastBaseFactor = (float)currentValues[1]; //PdfChunk chunkz; int numberOfSpaces; int lineLen; bool isJustified; float hangingCorrection = 0; float hScale = 1; float lastHScale = float.NaN; float baseWordSpacing = 0; float baseCharacterSpacing = 0; float glueWidth = 0; numberOfSpaces = line.NumberOfSpaces; lineLen = line.GetLineLengthUtf32(); // does the line need to be justified? isJustified = line.HasToBeJustified() && (numberOfSpaces != 0 || lineLen > 1); int separatorCount = line.GetSeparatorCount(); if (separatorCount > 0) { glueWidth = line.WidthLeft / separatorCount; } else if (isJustified) { if (line.NewlineSplit && line.WidthLeft >= (lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1))) { if (line.RTL) { text.MoveText(line.WidthLeft - lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1), 0); } baseWordSpacing = ratio * lastBaseFactor; baseCharacterSpacing = lastBaseFactor; } else { float width = line.WidthLeft; PdfChunk last = line.GetChunk(line.Size - 1); if (last != null) { String s = last.ToString(); char c; if (s.Length > 0 && hangingPunctuation.IndexOf((c = s[s.Length - 1])) >= 0) { float oldWidth = width; width += last.Font.Width(c) * 0.4f; hangingCorrection = width - oldWidth; } } float baseFactor = width / (ratio * numberOfSpaces + lineLen - 1); baseWordSpacing = ratio * baseFactor; baseCharacterSpacing = baseFactor; lastBaseFactor = baseFactor; } } int lastChunkStroke = line.LastStrokeChunk; int chunkStrokeIdx = 0; float xMarker = text.XTLM; float baseXMarker = xMarker; float yMarker = text.YTLM; bool adjustMatrix = false; float tabPosition = 0; // looping over all the chunks in 1 line foreach (PdfChunk chunk in line) { Color color = chunk.Color; hScale = 1; if (chunkStrokeIdx <= lastChunkStroke) { float width; if (isJustified) { width = chunk.GetWidthCorrected(baseCharacterSpacing, baseWordSpacing); } else { width = chunk.Width; } if (chunk.IsStroked()) { PdfChunk nextChunk = line.GetChunk(chunkStrokeIdx + 1); if (chunk.IsSeparator()) { width = glueWidth; Object[] sep = (Object[])chunk.GetAttribute(Chunk.SEPARATOR); IDrawInterface di = (IDrawInterface)sep[0]; bool vertical = (bool)sep[1]; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); if (vertical) { di.Draw(graphics, baseXMarker, yMarker + descender, baseXMarker + line.OriginalWidth, ascender - descender, yMarker); } else { di.Draw(graphics, xMarker, yMarker + descender, xMarker + width, ascender - descender, yMarker); } } if (chunk.IsTab()) { Object[] tab = (Object[])chunk.GetAttribute(Chunk.TAB); IDrawInterface di = (IDrawInterface)tab[0]; tabPosition = (float)tab[1] + (float)tab[3]; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); if (tabPosition > xMarker) { di.Draw(graphics, xMarker, yMarker + descender, tabPosition, ascender - descender, yMarker); } float tmp = xMarker; xMarker = tabPosition; tabPosition = tmp; } if (chunk.IsAttribute(Chunk.BACKGROUND)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.BACKGROUND)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); Object[] bgr = (Object[])chunk.GetAttribute(Chunk.BACKGROUND); graphics.SetColorFill((Color)bgr[0]); float[] extra = (float[])bgr[1]; graphics.Rectangle(xMarker - extra[0], yMarker + descender - extra[1] + chunk.TextRise, width - subtract + extra[0] + extra[2], ascender - descender + extra[1] + extra[3]); graphics.Fill(); graphics.SetGrayFill(0); } if (chunk.IsAttribute(Chunk.UNDERLINE)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.UNDERLINE)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object[][] unders = (Object[][])chunk.GetAttribute(Chunk.UNDERLINE); Color scolor = null; for (int k = 0; k < unders.Length; ++k) { Object[] obj = unders[k]; scolor = (Color)obj[0]; float[] ps = (float[])obj[1]; if (scolor == null) scolor = color; if (scolor != null) graphics.SetColorStroke(scolor); float fsize = chunk.Font.Size; graphics.SetLineWidth(ps[0] + fsize * ps[1]); float shift = ps[2] + fsize * ps[3]; int cap2 = (int)ps[4]; if (cap2 != 0) graphics.SetLineCap(cap2); graphics.MoveTo(xMarker, yMarker + shift); graphics.LineTo(xMarker + width - subtract, yMarker + shift); graphics.Stroke(); if (scolor != null) graphics.ResetGrayStroke(); if (cap2 != 0) graphics.SetLineCap(0); } graphics.SetLineWidth(1); } if (chunk.IsAttribute(Chunk.ACTION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.ACTION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; text.AddAnnotation(new PdfAnnotation(writer, xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size, (PdfAction)chunk.GetAttribute(Chunk.ACTION))); } if (chunk.IsAttribute(Chunk.REMOTEGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.REMOTEGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object[] obj = (Object[])chunk.GetAttribute(Chunk.REMOTEGOTO); String filename = (String)obj[0]; if (obj[1] is String) RemoteGoto(filename, (String)obj[1], xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); else RemoteGoto(filename, (int)obj[1], xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); } if (chunk.IsAttribute(Chunk.LOCALGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; LocalGoto((String)chunk.GetAttribute(Chunk.LOCALGOTO), xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); } if (chunk.IsAttribute(Chunk.LOCALDESTINATION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALDESTINATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; LocalDestination((String)chunk.GetAttribute(Chunk.LOCALDESTINATION), new PdfDestination(PdfDestination.XYZ, xMarker, yMarker + chunk.Font.Size, 0)); } if (chunk.IsAttribute(Chunk.GENERICTAG)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.GENERICTAG)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Rectangle rect = new Rectangle(xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size); IPdfPageEvent pev = writer.PageEvent; if (pev != null) pev.OnGenericTag(writer, this, rect, (String)chunk.GetAttribute(Chunk.GENERICTAG)); } if (chunk.IsAttribute(Chunk.PDFANNOTATION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.IsAttribute(Chunk.PDFANNOTATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; float fontSize = chunk.Font.Size; float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize); PdfAnnotation annot = PdfFormField.ShallowDuplicate((PdfAnnotation)chunk.GetAttribute(Chunk.PDFANNOTATION)); annot.Put(PdfName.RECT, new PdfRectangle(xMarker, yMarker + descender, xMarker + width - subtract, yMarker + ascender)); text.AddAnnotation(annot); } float[] paramsx = (float[])chunk.GetAttribute(Chunk.SKEW); object hs = chunk.GetAttribute(Chunk.HSCALE); if (paramsx != null || hs != null) { float b = 0, c = 0; if (paramsx != null) { b = paramsx[0]; c = paramsx[1]; } if (hs != null) hScale = (float)hs; text.SetTextMatrix(hScale, b, c, 1, xMarker, yMarker); } if (chunk.IsImage()) { Image image = chunk.Image; float[] matrix = image.Matrix; matrix[Image.CX] = xMarker + chunk.ImageOffsetX - matrix[Image.CX]; matrix[Image.CY] = yMarker + chunk.ImageOffsetY - matrix[Image.CY]; graphics.AddImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); text.MoveText(xMarker + lastBaseFactor + image.ScaledWidth - text.XTLM, 0); } } xMarker += width; ++chunkStrokeIdx; } if (chunk.Font.CompareTo(currentFont) != 0) { currentFont = chunk.Font; text.SetFontAndSize(currentFont.Font, currentFont.Size); } float rise = 0; Object[] textRender = (Object[])chunk.GetAttribute(Chunk.TEXTRENDERMODE); int tr = 0; float strokeWidth = 1; Color strokeColor = null; object fr = chunk.GetAttribute(Chunk.SUBSUPSCRIPT); if (textRender != null) { tr = (int)textRender[0] & 3; if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.SetTextRenderingMode(tr); if (tr == PdfContentByte.TEXT_RENDER_MODE_STROKE || tr == PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE) { strokeWidth = (float)textRender[1]; if (strokeWidth != 1) text.SetLineWidth(strokeWidth); strokeColor = (Color)textRender[2]; if (strokeColor == null) strokeColor = color; if (strokeColor != null) text.SetColorStroke(strokeColor); } } if (fr != null) rise = (float)fr; if (color != null) text.SetColorFill(color); if (rise != 0) text.SetTextRise(rise); if (chunk.IsImage()) { adjustMatrix = true; } else if (chunk.IsHorizontalSeparator()) { PdfTextArray array = new PdfTextArray(); array.Add(-glueWidth * 1000f / chunk.Font.Size / hScale); text.ShowText(array); } else if (chunk.IsTab()) { PdfTextArray array = new PdfTextArray(); array.Add((tabPosition - xMarker) * 1000f / chunk.Font.Size / hScale); text.ShowText(array); } // If it is a CJK chunk or Unicode TTF we will have to simulate the // space adjustment. else if (isJustified && numberOfSpaces > 0 && chunk.IsSpecialEncoding()) { if (hScale != lastHScale) { lastHScale = hScale; text.SetWordSpacing(baseWordSpacing / hScale); text.SetCharacterSpacing(baseCharacterSpacing / hScale); } String s = chunk.ToString(); int idx = s.IndexOf(' '); if (idx < 0) text.ShowText(s); else { float spaceCorrection = - baseWordSpacing * 1000f / chunk.Font.Size / hScale; PdfTextArray textArray = new PdfTextArray(s.Substring(0, idx)); int lastIdx = idx; while ((idx = s.IndexOf(' ', lastIdx + 1)) >= 0) { textArray.Add(spaceCorrection); textArray.Add(s.Substring(lastIdx, idx - lastIdx)); lastIdx = idx; } textArray.Add(spaceCorrection); textArray.Add(s.Substring(lastIdx)); text.ShowText(textArray); } } else { if (isJustified && hScale != lastHScale) { lastHScale = hScale; text.SetWordSpacing(baseWordSpacing / hScale); text.SetCharacterSpacing(baseCharacterSpacing / hScale); } text.ShowText(chunk.ToString()); } if (rise != 0) text.SetTextRise(0); if (color != null) text.ResetRGBColorFill(); if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); if (strokeColor != null) text.ResetRGBColorStroke(); if (strokeWidth != 1) text.SetLineWidth(1); if (chunk.IsAttribute(Chunk.SKEW) || chunk.IsAttribute(Chunk.HSCALE)) { adjustMatrix = true; text.SetTextMatrix(xMarker, yMarker); } } if (isJustified) { text.SetWordSpacing(0); text.SetCharacterSpacing(0); if (line.NewlineSplit) lastBaseFactor = 0; } if (adjustMatrix) text.MoveText(baseXMarker - text.XTLM, 0); currentValues[0] = currentFont; currentValues[1] = lastBaseFactor; }