Beispiel #1
0
 /**
 * Creates a new instance of the LineSeparator class.
 * @param lineWidth      the thickness of the line
 * @param percentage the width of the line as a percentage of the available page width
 * @param color          the color of the line
 * @param align          the alignment
 * @param offset     the offset of the line relative to the current baseline (negative = under the baseline)
 */
 public LineSeparator(float lineWidth, float percentage, BaseColor lineColor, int align, float offset) {
     this.lineWidth = lineWidth;
     this.percentage = percentage;
     this.lineColor = lineColor;
     this.alignment = align;
     this.offset = offset;
 }
Beispiel #2
0
            public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
                                         bool cached)
            {
                var soneFile = "";

                try
                {
                    soneFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                                                      "SIMSUN.TTC,1");
                }
                catch
                {
                    soneFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                                                      "MSYH.TTC,1");
                }
                BaseFont baseFont = BaseFont.CreateFont(soneFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                return(new Font(baseFont, size, style, color));
            }
Beispiel #3
0
 /** Places the barcode in a <CODE>PdfContentByte</CODE>. The
  * barcode is always placed at coodinates (0, 0). Use the
  * translation matrix to move it elsewhere.<p>
  * The bars and text are written in the following colors:<p>
  * <P><TABLE BORDER=1>
  * <TR>
  *    <TH><P><CODE>barColor</CODE></TH>
  *    <TH><P><CODE>textColor</CODE></TH>
  *    <TH><P>Result</TH>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P>bars and text painted with current fill color</TD>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>barColor</CODE></TD>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P>bars and text painted with <CODE>barColor</CODE></TD>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P><CODE>textColor</CODE></TD>
  *    <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>barColor</CODE></TD>
  *    <TD><P><CODE>textColor</CODE></TD>
  *    <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD>
  *    </TR>
  * </TABLE>
  * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed
  * @param barColor the color of the bars. It can be <CODE>null</CODE>
  * @param textColor the color of the text. It can be <CODE>null</CODE>
  * @return the dimensions the barcode occupies
  */    
 public override Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) {
     string fullCode = code;
     float fontX = 0;
     if (font != null) {
         if (generateChecksum && checksumText)
             fullCode += GetChecksum(fullCode);
         fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size);
     }
     string bCode = KeepNumbers(code);
     if (generateChecksum)
         bCode += GetChecksum(bCode);
     int len = bCode.Length;
     float fullWidth = len * (3 * x + 2 * x * n) + (6 + n ) * 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 = GetBarsInter25(bCode);
     bool print = true;
     if (barColor != null)
         cb.SetColorFill(barColor);
     for (int k = 0; k < bars.Length; ++k) {
         float w = (bars[k] == 0 ? x : x * n);
         if (print)
             cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight);
         print = !print;
         barStartX += w;
     }
     cb.Fill();
     if (font != null) {
         if (textColor != null)
             cb.SetColorFill(textColor);
         cb.BeginText();
         cb.SetFontAndSize(font, size);
         cb.SetTextMatrix(textStartX, textStartY);
         cb.ShowText(fullCode);
         cb.EndText();
     }
     return this.BarcodeSize;
 }   
 protected internal UncoloredPattern(PdfPatternPainter p, BaseColor color, float tint) : base(p) {
     this.color = color;
     this.tint = tint;
 }
 /** Sets the stroke color to an uncolored pattern.
  * @param p the pattern
  * @param color the color of the pattern
  */    
 public virtual void SetPatternStroke(PdfPatternPainter p, BaseColor color) {
     if (ExtendedColor.GetType(color) == ExtendedColor.TYPE_SEPARATION)
         SetPatternStroke(p, color, ((SpotColor)color).Tint);
     else
         SetPatternStroke(p, color, 0);
 }
 /**
  * Create a new uncolored tiling pattern.
  *
  * @param width the width of the pattern
  * @param height the height of the pattern
  * @param xstep the desired horizontal spacing between pattern cells.
  * May be either positive or negative, but not zero.
  * @param ystep the desired vertical spacing between pattern cells.
  * May be either positive or negative, but not zero.
  * @param color the default color. Can be <CODE>null</CODE>
  * @return the <CODE>PdfPatternPainter</CODE> where the pattern will be created
  */
 public PdfPatternPainter CreatePattern(float width, float height, float xstep, float ystep, BaseColor color) {
     CheckWriter();
     if ( xstep == 0.0f || ystep == 0.0f )
         throw new Exception(MessageLocalization.GetComposedMessage("xstep.or.ystep.can.not.be.zero"));
     PdfPatternPainter painter = new PdfPatternPainter(writer, color);
     painter.Width = width;
     painter.Height = height;
     painter.XStep = xstep;
     painter.YStep = ystep;
     writer.AddSimplePattern(painter);
     return painter;
 }
Beispiel #7
0
        public void BarcodesTest1() {
            Document document = new Document();
            PdfAWriter writer = PdfAWriter.GetInstance(document, new
                FileStream(OUT + "barcodesTest1.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3A);

            writer.SetTagged();
            document.Open();
            writer.ViewerPreferences = PdfWriter.DisplayDocTitle;
            document.AddTitle("Some title");
            document.AddLanguage("en-us");
            writer.CreateXmpMetadata();

            document.NewPage();

            // Set output intent. PDF/A requirement.
            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open,
                FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();
            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            // All fonts shall be embedded. PDF/A requirement.
            Font normal9 = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 9);
            Font normal8 = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 8);

            BaseColor color = new BaseColor(111, 211, 11);
            normal8.Color = color;

            PdfContentByte cb = writer.DirectContent;

            String code = "119716-500023718";
            Barcode barcode = new Barcode39();
            barcode.Code = code;
            barcode.StartStopText = false;
            barcode.Font = normal9.BaseFont;
            barcode.Extended = true;

            Image image = barcode.CreateImageWithBarcode(cb, color, color);
            image.Alt = "Bla Bla";
            document.Add(image);

            document.Close();
        }
Beispiel #8
0
 /** Sets the stroke color. <CODE>color</CODE> can be an
  * <CODE>ExtendedColor</CODE>.
  * @param color the color
  */    
 public virtual void SetColorStroke(BaseColor value) {
     PdfWriter.CheckPdfIsoConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, value);
     int type = ExtendedColor.GetType(value);
     switch (type) {
         case ExtendedColor.TYPE_GRAY: {
             SetGrayStroke(((GrayColor)value).Gray);
             break;
         }
         case ExtendedColor.TYPE_CMYK: {
             CMYKColor cmyk = (CMYKColor)value;
             SetCMYKColorStrokeF(cmyk.Cyan, cmyk.Magenta, cmyk.Yellow, cmyk.Black);
             break;
         }
         case ExtendedColor.TYPE_SEPARATION: {
             SpotColor spot = (SpotColor)value;
             SetColorStroke(spot.PdfSpotColor, spot.Tint);
             break;
         }
         case ExtendedColor.TYPE_PATTERN: {
             PatternColor pat = (PatternColor)value;
             SetPatternStroke(pat.Painter);
             break;
         }
         case ExtendedColor.TYPE_SHADING: {
             ShadingColor shading = (ShadingColor)value;
             SetShadingStroke(shading.PdfShadingPattern);
             break;
         }
         default:
             SetRGBColorStroke(value.R, value.G, value.B);
             break;
     }
 }
Beispiel #9
0
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            Font     normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);

            float height = writer.PageSize.Height, width = writer.PageSize.Width;
            float marginLeft = document.LeftMargin - 10, marginTop = document.TopMargin, marginRight = document.RightMargin - 10;

            cb.SetFontAndSize(bf, 8);

            #region LEFT

            var branchOfficeY = height - marginTop + 50;
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " HEAD OFFICE :", marginLeft, branchOfficeY, 0);
            string[] branchOffices =
            {
                " Cable   : DANLIRIS",
                " Phone   : (62271)740888, 714400",
                " Website : www.danliris.com",
                " Fax. : (62271)740777, 735222",
            };
            for (int i = 0; i < branchOffices.Length; i++)
            {
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, branchOffices[i], marginLeft, branchOfficeY - 10 - (i * 10), 0);
            }

            #endregion

            #region CENTER

            var headOfficeX = width / 2 + 30;
            var headOfficeY = height - marginTop + 60;


            string[] headOffices =
            {
                "                                                                                                                                                                      Ref. No. : FM-00-SP-24-004",
                "P.T. DAN LIRIS",
                "SPINNING - WEAVING - FINISHING - PRINTING - GARMENT",
                "JL. MERAPI No. 23, KEL. BANARAN, KEC. GROGOL, SUKOHARJO - INDONESIA",
                "PO. BOX 166 SOLO 57100",
                "                                                                                                                                                                                        Page " + (writer.PageNumber),
                // " "
            };
            for (int i = 0; i < headOffices.Length; i++)
            {
                cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, headOffices[i], headOfficeX, headOfficeY - (i * 10), 0);
            }

            #endregion


            #region RIGHT

            BaseColor grey = new BaseColor(128, 128, 128);
            //cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Page " + (writer.PageNumber), width - (1 / 2) - marginRight, height - marginTop + 20, 0);

            #endregion


            cb.EndText();
        }
Beispiel #10
0
        /**
         * Creates a Font object based on a chain of properties.
         * @param   chain   chain of properties
         * @return  an iText Font object
         */
        public Font GetFont(ChainedProperties chain)
        {
            // [1] font name

            String face = chain[HtmlTags.FACE];

            // try again, under the CSS key.
            //ISSUE: If both are present, we always go with face, even if font-family was
            //  defined more recently in our ChainedProperties.  One solution would go like this:
            //    Map all our supported style attributes to the 'normal' tag name, so we could
            //    look everything up under that one tag, retrieving the most current value.
            if (face == null || face.Trim().Length == 0)
            {
                face = chain[HtmlTags.FONTFAMILY];
            }
            // if the font consists of a comma separated list,
            // take the first font that is registered
            if (face != null)
            {
                StringTokenizer tok = new StringTokenizer(face, ",");
                while (tok.HasMoreTokens())
                {
                    face = tok.NextToken().Trim();
                    if (face.StartsWith("\""))
                    {
                        face = face.Substring(1);
                    }
                    if (face.EndsWith("\""))
                    {
                        face = face.Substring(0, face.Length - 1);
                    }
                    if (provider.IsRegistered(face))
                    {
                        break;
                    }
                }
            }

            // [2] encoding
            String encoding = chain[HtmlTags.ENCODING];

            if (encoding == null)
            {
                encoding = BaseFont.WINANSI;
            }

            // [3] embedded

            // [4] font size
            String value = chain[HtmlTags.SIZE];
            float  size  = 12;

            if (value != null)
            {
                size = float.Parse(value, CultureInfo.InvariantCulture);
            }

            // [5] font style
            int style = 0;

            // text-decoration
            String decoration = chain[HtmlTags.TEXTDECORATION];

            if (decoration != null && decoration.Trim().Length != 0)
            {
                if (HtmlTags.UNDERLINE.Equals(decoration))
                {
                    style |= Font.UNDERLINE;
                }
                else if (HtmlTags.LINETHROUGH.Equals(decoration))
                {
                    style |= Font.STRIKETHRU;
                }
            }
            // italic
            if (chain.HasProperty(HtmlTags.I))
            {
                style |= Font.ITALIC;
            }
            // bold
            if (chain.HasProperty(HtmlTags.B))
            {
                style |= Font.BOLD;
            }
            // underline
            if (chain.HasProperty(HtmlTags.U))
            {
                style |= Font.UNDERLINE;
            }
            // strikethru
            if (chain.HasProperty(HtmlTags.S))
            {
                style |= Font.STRIKETHRU;
            }

            // [6] Color
            BaseColor color = HtmlUtilities.DecodeColor(chain[HtmlTags.COLOR]);

            // Get the font object from the provider
            return(provider.GetFont(face, encoding, true, size, style, color));
        }
Beispiel #11
0
        /**
         * Method contributed by Lubos Strapko
         * @param h
         * @param chain
         * @since 2.1.3
         */
        public static void ResolveStyleAttribute(IDictionary <String, String> h, ChainedProperties chain)
        {
            String style;

            h.TryGetValue(HtmlTags.STYLE, out style);
            if (style == null)
            {
                return;
            }
            Properties prop = HtmlUtilities.ParseAttributes(style);

            foreach (string key in prop.Keys)
            {
                if (key.Equals(HtmlTags.FONTFAMILY))
                {
                    h[HtmlTags.FACE] = prop[key];
                }
                else if (key.Equals(HtmlTags.FONTSIZE))
                {
                    float actualFontSize = HtmlUtilities.ParseLength(chain[HtmlTags.SIZE],
                                                                     HtmlUtilities.DEFAULT_FONT_SIZE);
                    if (actualFontSize <= 0f)
                    {
                        actualFontSize = HtmlUtilities.DEFAULT_FONT_SIZE;
                    }
                    h[HtmlTags.SIZE] = HtmlUtilities.ParseLength(prop[key], actualFontSize).ToString(CultureInfo.InvariantCulture) + "pt";
                }
                else if (key.Equals(HtmlTags.FONTSTYLE))
                {
                    String ss = prop[key].Trim().ToLowerInvariant();
                    if (ss.Equals(HtmlTags.ITALIC) || ss.Equals(HtmlTags.OBLIQUE))
                    {
                        h[HtmlTags.I] = null;
                    }
                }
                else if (key.Equals(HtmlTags.FONTWEIGHT))
                {
                    String ss = prop[key].Trim().ToLowerInvariant();
                    if (ss.Equals(HtmlTags.BOLD) || ss.Equals("700") || ss.Equals("800") ||
                        ss.Equals("900"))
                    {
                        h[HtmlTags.B] = null;
                    }
                }
                else if (key.Equals(HtmlTags.TEXTDECORATION))
                {
                    String ss = prop[key].Trim().ToLowerInvariant();
                    if (ss.Equals(HtmlTags.UNDERLINE))
                    {
                        h[HtmlTags.U] = null;
                    }
                }
                else if (key.Equals(HtmlTags.COLOR))
                {
                    BaseColor c = HtmlUtilities.DecodeColor(prop[key]);
                    if (c != null)
                    {
                        int    hh = c.ToArgb();
                        String hs = hh.ToString("x");
                        hs = "000000" + hs;
                        hs = "#" + hs.Substring(hs.Length - 6);
                        h[HtmlTags.COLOR] = hs;
                    }
                }
                else if (key.Equals(HtmlTags.LINEHEIGHT))
                {
                    String ss             = prop[key].Trim();
                    float  actualFontSize = HtmlUtilities.ParseLength(chain[HtmlTags.SIZE],
                                                                      HtmlUtilities.DEFAULT_FONT_SIZE);
                    if (actualFontSize <= 0f)
                    {
                        actualFontSize = HtmlUtilities.DEFAULT_FONT_SIZE;
                    }
                    float v = HtmlUtilities.ParseLength(prop[key],
                                                        actualFontSize);
                    if (ss.EndsWith("%"))
                    {
                        h[HtmlTags.LEADING] = "0," + v / 100;
                        return;
                    }
                    if (Util.EqualsIgnoreCase(HtmlTags.NORMAL, ss))
                    {
                        h[HtmlTags.LEADING] = "0,1.5";
                        return;
                    }
                    h[HtmlTags.LEADING] = v + ",0";
                }
                else if (key.Equals(HtmlTags.TEXTALIGN))
                {
                    String ss = prop[key].Trim().ToLowerInvariant();
                    h[HtmlTags.ALIGN] = ss;
                }
                else if (key.Equals(HtmlTags.PADDINGLEFT))
                {
                    String ss = prop[key].Trim().ToLowerInvariant();
                    h[HtmlTags.INDENT] = HtmlUtilities.ParseLength(ss).ToString(CultureInfo.InvariantCulture);
                }
            }
        }
 /// <summary>
 /// Sets the colour of this RtfParagraphStyle.
 /// </summary>
 /// <param name="color">The Color to use.</param>
 public void SetColor(BaseColor color)
 {
     _modified = _modified | ModifiedFontColor;
     Color     = color;
 }
 /// <summary>
 /// Constructs a new RtfParagraphStyle with the given attributes.
 /// </summary>
 /// <param name="styleName">The name of this RtfParagraphStyle.</param>
 /// <param name="fontName">The name of the font to use for this RtfParagraphStyle.</param>
 /// <param name="fontSize">The size of the font to use for this RtfParagraphStyle.</param>
 /// <param name="fontStyle">The style of the font to use for this RtfParagraphStyle.</param>
 /// <param name="fontColor">The colour of the font to use for this RtfParagraphStyle.</param>
 public RtfParagraphStyle(string styleName, string fontName, int fontSize, int fontStyle, BaseColor fontColor) : base(null, new RtfFont(fontName, fontSize, fontStyle, fontColor))
 {
     _styleName = styleName;
 }
        /**
         * The ListCssApplier has the capabilities to change the type of the given {@link List} dependable on the css.
         * This means: <strong>Always replace your list with the returned one and add content to the list after applying!</strong>
         */
        // not implemented: list-style-type:armenian, georgian, decimal-leading-zero.
        public List Apply(List list, Tag t, IImageProvider htmlPipelineContext)
        {
            float fontSize = FontSizeTranslator.GetInstance().GetFontSize(t);
            List  lst      = list;
            IDictionary <String, String> css = t.CSS;
            String styleType;

            css.TryGetValue(CSS.Property.LIST_STYLE_TYPE, out styleType);
            BaseColor color = HtmlUtilities.DecodeColor(css.ContainsKey(CSS.Property.COLOR) ? css[CSS.Property.COLOR] : null);

            if (null == color)
            {
                color = BaseColor.BLACK;
            }

            if (null != styleType)
            {
                if (Util.EqualsIgnoreCase(styleType, CSS.Value.NONE))
                {
                    lst.Lettered = false;
                    lst.Numbered = false;
                    lst.SetListSymbol("");
                }
                else if (Util.EqualsIgnoreCase(CSS.Value.DECIMAL, styleType))
                {
                    lst = new List(List.ORDERED);
                    SynchronizeSymbol(fontSize, lst, color);
                }
                else if (Util.EqualsIgnoreCase(CSS.Value.DISC, styleType))
                {
                    lst              = new ZapfDingbatsList(108);
                    lst.Autoindent   = false;
                    lst.SymbolIndent = 7.75f;
                    Chunk symbol = lst.Symbol;
                    symbol.SetTextRise(1.5f);
                    Font font = symbol.Font;
                    font.Size  = 4.5f;
                    font.Color = color;
                }
                else if (Util.EqualsIgnoreCase(CSS.Value.SQUARE, styleType))
                {
                    lst = new ZapfDingbatsList(110);
                    ShrinkSymbol(lst, fontSize, color);
                }
                else if (Util.EqualsIgnoreCase(CSS.Value.CIRCLE, styleType))
                {
                    lst              = new ZapfDingbatsList(109);
                    lst.Autoindent   = false;
                    lst.SymbolIndent = 7.75f;
                    Chunk symbol = lst.Symbol;
                    symbol.SetTextRise(1.5f);
                    Font font = symbol.Font;
                    font.Size  = 4.5f;
                    font.Color = color;
                }
                else if (CSS.Value.LOWER_ROMAN.Equals(styleType))
                {
                    lst            = new RomanList(true, 0);
                    lst.Autoindent = true;
                    SynchronizeSymbol(fontSize, lst, color);
                }
                else if (CSS.Value.UPPER_ROMAN.Equals(styleType))
                {
                    lst = new RomanList(false, 0);
                    SynchronizeSymbol(fontSize, lst, color);
                    lst.Autoindent = true;
                }
                else if (CSS.Value.LOWER_GREEK.Equals(styleType))
                {
                    lst = new GreekList(true, 0);
                    SynchronizeSymbol(fontSize, lst, color);
                    lst.Autoindent = true;
                }
                else if (CSS.Value.UPPER_GREEK.Equals(styleType))
                {
                    lst = new GreekList(false, 0);
                    SynchronizeSymbol(fontSize, lst, color);
                    lst.Autoindent = true;
                }
                else if (CSS.Value.LOWER_ALPHA.Equals(styleType) || CSS.Value.LOWER_LATIN.Equals(styleType))
                {
                    lst = new List(List.ORDERED, List.ALPHABETICAL);
                    SynchronizeSymbol(fontSize, lst, color);
                    lst.Lowercase  = true;
                    lst.Autoindent = true;
                }
                else if (CSS.Value.UPPER_ALPHA.Equals(styleType) || CSS.Value.UPPER_LATIN.Equals(styleType))
                {
                    lst = new List(List.ORDERED, List.ALPHABETICAL);
                    SynchronizeSymbol(fontSize, lst, color);
                    lst.Lowercase  = false;
                    lst.Autoindent = true;
                }
            }
            else if (Util.EqualsIgnoreCase(t.Name, HTML.Tag.OL))
            {
                lst = new List(List.ORDERED);
                SynchronizeSymbol(fontSize, lst, color);
                lst.Autoindent = true;
            }
            else if (Util.EqualsIgnoreCase(t.Name, HTML.Tag.UL))
            {
                lst = new List(List.UNORDERED);
                ShrinkSymbol(lst, fontSize, color);
            }
            if (css.ContainsKey(CSS.Property.LIST_STYLE_IMAGE) &&
                !Util.EqualsIgnoreCase(css[CSS.Property.LIST_STYLE_IMAGE], CSS.Value.NONE))
            {
                lst = new List();
                String url = utils.ExtractUrl(css[CSS.Property.LIST_STYLE_IMAGE]);
                iTextSharp.text.Image img = null;
                try {
                    if (htmlPipelineContext == null)
                    {
                        img = new ImageRetrieve().RetrieveImage(url);
                    }
                    else
                    {
                        try {
                            img = new ImageRetrieve(htmlPipelineContext).RetrieveImage(url);
                        } catch (NoImageException) {
                            if (LOG.IsLogging(Level.TRACE))
                            {
                                LOG.Trace(String.Format(LocaleMessages.GetInstance().GetMessage("css.applier.list.noimage")));
                            }
                            img = new ImageRetrieve().RetrieveImage(url);
                        }
                    }
                    lst.ListSymbol   = new Chunk(img, 0, 0, false);
                    lst.SymbolIndent = img.Width;
                    if (LOG.IsLogging(Level.TRACE))
                    {
                        LOG.Trace(String.Format(LocaleMessages.GetInstance().GetMessage("html.tag.list"), url));
                    }
                } catch (IOException e) {
                    if (LOG.IsLogging(Level.ERROR))
                    {
                        LOG.Error(String.Format(LocaleMessages.GetInstance().GetMessage("html.tag.list.failed"), url), e);
                    }
                    lst = new List(List.UNORDERED);
                } catch (NoImageException e) {
                    if (LOG.IsLogging(Level.ERROR))
                    {
                        LOG.Error(e.Message, e);
                    }
                    lst = new List(List.UNORDERED);
                }
                lst.Autoindent = false;
            }
            lst.Alignindent = false;
            float leftIndent = 0;

            if (css.ContainsKey(CSS.Property.LIST_STYLE_POSITION) && Util.EqualsIgnoreCase(css[CSS.Property.LIST_STYLE_POSITION], CSS.Value.INSIDE))
            {
                leftIndent += 30;
            }
            else
            {
                leftIndent += 15;
            }
            leftIndent         += css.ContainsKey(CSS.Property.MARGIN_LEFT)?utils.ParseValueToPt(css[CSS.Property.MARGIN_LEFT], fontSize):0;
            leftIndent         += css.ContainsKey(CSS.Property.PADDING_LEFT)?utils.ParseValueToPt(css[CSS.Property.PADDING_LEFT], fontSize):0;
            lst.IndentationLeft = leftIndent;
            return(lst);
        }
        private static void loadContents(Document doc, Hashtable htImportacao, bool temErros)
        {
            string strAux = string.Empty;

            Font arial14BoldBlack = PdfMetodosAuxiliares.GerarFonte(tipoFonte.Arial, 14, Font.BOLD, BaseColor.BLACK);
            Font arial14BoldGreen = PdfMetodosAuxiliares.GerarFonte(tipoFonte.Arial, 14, Font.BOLD, BaseColor.GREEN);
            Font arial14BoldRed   = PdfMetodosAuxiliares.GerarFonte(tipoFonte.Arial, 14, Font.BOLD, BaseColor.RED);

            Font arial10BoldRed  = PdfMetodosAuxiliares.GerarFonte(tipoFonte.Arial, 10, Font.BOLD, BaseColor.RED);
            Font arial10BoldBlue = PdfMetodosAuxiliares.GerarFonte(tipoFonte.Arial, 10, Font.BOLD, new BaseColor(0x0000EE));

            BaseColor corCinzaClaro = new BaseColor(220, 220, 220);

            #region Dados

            List <Hashtable> alErrosEspaciais   = hasKey(htImportacao, "ERROS_ESPACIAIS") ? htImportacao["ERROS_ESPACIAIS"] as List <Hashtable> : null;
            List <Hashtable> alObrigatoriedades = hasKey(htImportacao, "OBRIGATORIEDADES") ? htImportacao["OBRIGATORIEDADES"] as List <Hashtable> : null;
            List <Hashtable> alAtributos        = hasKey(htImportacao, "ATRIBUTOS") ? htImportacao["ATRIBUTOS"] as List <Hashtable> : null;
            List <Hashtable> alGeometrias       = hasKey(htImportacao, "GEOMETRIAS") ? htImportacao["GEOMETRIAS"] as List <Hashtable> : null;

            #endregion

            PdfPTable tabelaLinha     = null;
            PdfPTable tabelaDocumento = null;

            tabelaDocumento = new PdfPTable(1);
            tabelaDocumento.WidthPercentage = 100;
            tabelaDocumento.SetWidths(new float[] { 100 });
            tabelaDocumento.SplitLate = false;
            tabelaDocumento.SplitRows = true;

            tabelaDocumento.DefaultCell.Border              = 0;
            tabelaDocumento.DefaultCell.PaddingLeft         = 2;
            tabelaDocumento.DefaultCell.PaddingRight        = 2;
            tabelaDocumento.DefaultCell.PaddingBottom       = 2;
            tabelaDocumento.DefaultCell.PaddingTop          = 2;
            tabelaDocumento.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
            tabelaDocumento.HeaderRows = 1;


            #region Título

            tabelaDocumento.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
            tabelaDocumento.AddCell(new Phrase(new Chunk("Relatório de Importação", arial14BoldBlack)));
            tabelaDocumento.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
            tabelaDocumento.AddCell("\n");

            #endregion


            #region Situação

            tabelaDocumento.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

            if (!temErros)
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Dados Aprovados", arial14BoldGreen)));
            }
            else
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Dados Inválidos", arial14BoldRed)));
            }

            tabelaDocumento.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;

            tabelaDocumento.AddCell("\n");

            #endregion


            #region Erros Espaciais

            if (alErrosEspaciais != null && alErrosEspaciais.Count > 0)
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Erros Espaciais", arial10BoldRed)));

                tabelaLinha = new PdfPTable(new float[] { 30, 70 });
                tabelaLinha.DefaultCell.PaddingLeft     = 3;
                tabelaLinha.DefaultCell.PaddingRight    = 3;
                tabelaLinha.DefaultCell.PaddingBottom   = 3;
                tabelaLinha.DefaultCell.PaddingTop      = 3;
                tabelaLinha.DefaultCell.BackgroundColor = corCinzaClaro;

                tabelaLinha.AddCell(new Phrase(new Chunk("Tabela", PdfMetodosAuxiliares.arial8Negrito)));
                tabelaLinha.AddCell(new Phrase(new Chunk("Erro", PdfMetodosAuxiliares.arial8Negrito)));

                tabelaLinha.DefaultCell.BackgroundColor = null;

                foreach (Hashtable htErroEspacial in alErrosEspaciais)
                {
                    strAux = hasKey(htErroEspacial, "SIGLA_TABELA") ? htErroEspacial["SIGLA_TABELA"].ToString() : string.Empty;
                    tabelaLinha.AddCell(new Phrase(new Chunk(strAux, PdfMetodosAuxiliares.arial8)));

                    strAux = hasKey(htErroEspacial, "DESCRICAO_MENSAGEM") ? htErroEspacial["DESCRICAO_MENSAGEM"].ToString() : string.Empty;
                    tabelaLinha.AddCell(new Phrase(new Chunk(strAux, PdfMetodosAuxiliares.arial8)));
                }

                tabelaDocumento.AddCell(tabelaLinha);
            }
            else
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Erros Espaciais", arial10BoldBlue)));
                tabelaDocumento.AddCell(new Phrase(new Chunk("- Nenhum erro espacial foi encontrado.", PdfMetodosAuxiliares.arial8)));
            }
            tabelaDocumento.AddCell("\n");

            #endregion


            #region Obrigatoriedades

            if (alObrigatoriedades != null && alObrigatoriedades.Count > 0)
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Obrigatoriedades", arial10BoldRed)));


                tabelaLinha = new PdfPTable(new float[] { 100 });
                tabelaLinha.DefaultCell.PaddingLeft     = 3;
                tabelaLinha.DefaultCell.PaddingRight    = 3;
                tabelaLinha.DefaultCell.PaddingBottom   = 3;
                tabelaLinha.DefaultCell.PaddingTop      = 3;
                tabelaLinha.DefaultCell.BackgroundColor = corCinzaClaro;

                tabelaLinha.AddCell(new Phrase(new Chunk("Validações", PdfMetodosAuxiliares.arial8Negrito)));

                tabelaLinha.DefaultCell.BackgroundColor = null;

                foreach (Hashtable htObrigatoriedade in alObrigatoriedades)
                {
                    strAux = hasKey(htObrigatoriedade, "DESCRICAO_MENSAGEM") ? htObrigatoriedade["DESCRICAO_MENSAGEM"].ToString() : string.Empty;
                    tabelaLinha.AddCell(new Phrase(new Chunk(strAux, PdfMetodosAuxiliares.arial8)));
                }

                tabelaDocumento.AddCell(tabelaLinha);
            }
            else
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Obrigatoriedades", arial10BoldBlue)));
                tabelaDocumento.AddCell(new Phrase(new Chunk("- Todas as obrigatoriedades foram atendidas.", PdfMetodosAuxiliares.arial8)));
            }
            tabelaDocumento.AddCell("\n");

            #endregion


            #region Atributos

            if (alAtributos != null && alAtributos.Count > 0)
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Atributos", arial10BoldRed)));


                tabelaLinha = new PdfPTable(new float[] { 20, 80 });
                tabelaLinha.DefaultCell.PaddingLeft     = 3;
                tabelaLinha.DefaultCell.PaddingRight    = 3;
                tabelaLinha.DefaultCell.PaddingBottom   = 3;
                tabelaLinha.DefaultCell.PaddingTop      = 3;
                tabelaLinha.DefaultCell.BackgroundColor = corCinzaClaro;

                tabelaLinha.AddCell(new Phrase(new Chunk("Tabela", PdfMetodosAuxiliares.arial8Negrito)));
                tabelaLinha.AddCell(new Phrase(new Chunk("Erro", PdfMetodosAuxiliares.arial8Negrito)));

                tabelaLinha.DefaultCell.BackgroundColor = null;

                foreach (Hashtable htAtributo in alAtributos)
                {
                    strAux = hasKey(htAtributo, "SIGLA_TABELA") ? htAtributo["SIGLA_TABELA"].ToString() : string.Empty;
                    tabelaLinha.AddCell(new Phrase(new Chunk(strAux, PdfMetodosAuxiliares.arial8)));

                    strAux = hasKey(htAtributo, "DESCRICAO_MENSAGEM") ? htAtributo["DESCRICAO_MENSAGEM"].ToString() : string.Empty;
                    tabelaLinha.AddCell(new Phrase(new Chunk(strAux, PdfMetodosAuxiliares.arial8)));
                }

                tabelaDocumento.AddCell(tabelaLinha);
            }
            else
            {
                tabelaDocumento.AddCell(new Phrase(new Chunk("Atributos", arial10BoldBlue)));
                tabelaDocumento.AddCell(new Phrase(new Chunk("- Nenhum erro nos atributos foi encontrado.", PdfMetodosAuxiliares.arial8)));
            }
            tabelaDocumento.AddCell("\n");
            #endregion


            #region Geometrias (Quantidade)

            tabelaDocumento.AddCell(new Phrase(new Chunk("Geometrias", arial10BoldBlue)));

            tabelaLinha = new PdfPTable(new float[] { 70, 30 });
            tabelaLinha.DefaultCell.PaddingLeft     = 3;
            tabelaLinha.DefaultCell.PaddingRight    = 3;
            tabelaLinha.DefaultCell.PaddingBottom   = 3;
            tabelaLinha.DefaultCell.PaddingTop      = 3;
            tabelaLinha.DefaultCell.BackgroundColor = corCinzaClaro;

            tabelaLinha.AddCell(new Phrase(new Chunk("Tabela", PdfMetodosAuxiliares.arial8Negrito)));
            tabelaLinha.AddCell(new Phrase(new Chunk("Quantidade", PdfMetodosAuxiliares.arial8Negrito)));

            tabelaLinha.DefaultCell.BackgroundColor = null;

            if (alGeometrias != null)
            {
                foreach (Hashtable htGeometria in alGeometrias)
                {
                    strAux  = htGeometria["SIGLA_TABELA"].ToString();
                    strAux += hasKey(htGeometria, "NOME_TABELA") ? " - " + htGeometria["NOME_TABELA"].ToString() : string.Empty;

                    tabelaLinha.AddCell(new Phrase(new Chunk(strAux, PdfMetodosAuxiliares.arial8)));

                    strAux = hasKey(htGeometria, "DESCRICAO_MENSAGEM") ? htGeometria["DESCRICAO_MENSAGEM"].ToString() : string.Empty;
                    tabelaLinha.AddCell(new Phrase(new Chunk(strAux, PdfMetodosAuxiliares.arial8)));
                }
            }

            tabelaDocumento.AddCell(tabelaLinha);

            #endregion


            doc.Add(tabelaDocumento);
        }
 public virtual void PlaceBarcode(PdfContentByte cb, BaseColor foreground, float moduleHeight, float moduleWidth) {
     PaintCode();
     int stride = (bitColumns + 7)/8;
     cb.SetColorFill(foreground);
     for (int k = 0; k < codeRows; ++k) {
         int p = k*stride;
         for (int j = 0; j < bitColumns; ++j) {
             int b = outBits[p + j/8] & 0xff;
             b <<= j%8;
             if ((b & 0x80) != 0) {
                 cb.Rectangle(j*moduleWidth, (codeRows - k - 1)*moduleHeight, moduleWidth, moduleHeight);
             }
         }
     }
     cb.Fill();
 }
Beispiel #17
0
 private Phrase ComposePhrase(String text, BaseFont ufont, BaseColor color, float fontSize) {
     Phrase phrase = null;
     if (extensionFont == null && (substitutionFonts == null || substitutionFonts.Count == 0))
         phrase = new Phrase(new Chunk(text, new Font(ufont, fontSize, 0, color)));
     else {
         FontSelector fs = new FontSelector();
         fs.AddFont(new Font(ufont, fontSize, 0, color));
         if (extensionFont != null)
             fs.AddFont(new Font(extensionFont, fontSize, 0, color));
         if (substitutionFonts != null) {
             foreach (BaseFont bf in substitutionFonts) {
                 fs.AddFont(new Font(bf, fontSize, 0, color));
             }
         }
         phrase = fs.Process(text);
     }
     return phrase;
 }
Beispiel #18
0
        /// <summary>
        /// Writes text to PDF file on desired position and creates new PDF file.
        /// </summary>
        /// <param name="originalPDFpath"> Path to original PDF file. </param>
        /// <param name="newPDFpath"> Path of PDF to be created. </param>
        /// <param name="valueToWrite"> Text string to be written. </param>
        /// <param name="writeOnPage"> Page of PDF. </param>
        /// <param name="fontFamily"> Font family. </param>
        /// <param name="fontSize"> Font size. </param>
        /// <param name="fontColorHex"> Color of font. </param>
        /// <param name="coordinateX"> X coordinate. </param>
        /// <param name="coordinateY"> Y coordinate. </param>
        /// <returns></returns>
        public static bool WriteText(string originalPDFpath, string newPDFpath, string valueToWrite, int writeOnPage, string fontFamily, decimal fontSize, string fontColorHex, int coordinateX, int coordinateY)
        {
            bool res = false;

            SetPDFPagesCount(originalPDFpath);
            //string s = Path.GetDirectoryName(originalPDFpath);


            /*  File.Copy(originalPDFpath, newPDFpath);
             * Color color = System.Drawing.ColorTranslator.FromHtml(fontColorHex);
             * BaseColor bs = new BaseColor(color);
             * iTextSharp.text.Font arial = FontFactory.GetFont("Arial", 50, BaseColor.BLUE);
             * iTextSharp.text.Font font = FontFactory.GetFont(fontFamily,Int32.Parse(fontSize.ToString()), bs);
             * Phrase phrase = new Phrase(writeValue, arial);
             * Document doc = new Document();
             * iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
             *    new System.IO.FileStream(newPDFpath,
             *        System.IO.FileMode.Open));
             * doc.Open();
             * PdfContentByte canvas = writer.DirectContent;
             * ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, phrase, coordinateX, coordinateY,1);*/

            PdfReader reader = new PdfReader(originalPDFpath);

            iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
            Document document = new Document(size);

            // open the writer
            FileStream fs     = new FileStream(newPDFpath, FileMode.Create, FileAccess.Write);
            PdfWriter  writer = PdfWriter.GetInstance(document, fs);

            document.Open();

            // the pdf content
            PdfContentByte cb  = writer.DirectContent;
            PdfContentByte cb2 = writer.DirectContent;

            Color     color   = System.Drawing.ColorTranslator.FromHtml(fontColorHex);
            BaseColor bs      = new BaseColor(color);
            BaseFont  bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);

            for (int i = 1; i < pdfPages + 1; i++)
            {
                if (i == writeOnPage)
                {
                    document.NewPage();
                    PdfImportedPage page   = writer.GetImportedPage(reader, writeOnPage);
                    int             curRot = reader.GetPageRotation(i);

                    cb.SetColorFill(bs);

                    cb.SetFontAndSize(bfTimes, Int32.Parse(fontSize.ToString()));

                    // write the text in the pdf content
                    cb.BeginText();
                    // put the alignment and coordinates here
                    cb.ShowTextAligned(1, valueToWrite, coordinateX, coordinateY, 0);
                    cb.EndText();
                    switch (curRot)
                    {
                    case 0:
                        writer.DirectContent.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                        break;

                    case 90:
                        writer.DirectContent.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                        break;

                    case 180:
                        writer.DirectContent.AddTemplate(page, -1f, 0, 0, -1f, reader.GetPageSizeWithRotation(i).Width, reader.GetPageSizeWithRotation(i).Height);
                        break;

                    case 270:
                        writer.DirectContent.AddTemplate(page, 0, 1f, -1f, 0, reader.GetPageSizeWithRotation(i).Width, 0);
                        break;
                    }
                }
                else
                {
                    if (i > 1)
                    {
                        document.NewPage();
                    }
                    PdfImportedPage page2 = writer.GetImportedPage(reader, i);
                    cb2.AddTemplate(page2, 0, 0);
                }
            }

            // close the streams and voilá the file should be changed :)
            document.Close();
            fs.Close();
            writer.Close();
            reader.Close();


            /*
             * //creates empty pdf
             * Document document = new Document();
             *
             * FileStream fs = new FileStream(originalPDFpath, FileMode.OpenOrCreate);
             * PdfWriter.GetInstance(document, fs);
             * document.Open();
             * document.Add(new Paragraph("Hello World"));
             * document.Add(new Paragraph(DateTime.Now.ToString()));
             *
             * document.Close();
             * fs.Close();
             */
            return(res);
        }
Beispiel #19
0
 /** Sets the stroke color. <CODE>color</CODE> can be an
  * <CODE>ExtendedColor</CODE>.
  * @param color the color
  */    
 public virtual void SetColorStroke(BaseColor value) {
     int type = ExtendedColor.GetType(value);
     switch (type) {
         case ExtendedColor.TYPE_GRAY: {
             SetGrayStroke(((GrayColor)value).Gray);
             break;
         }
         case ExtendedColor.TYPE_CMYK: {
             CMYKColor cmyk = (CMYKColor)value;
             SetCMYKColorStrokeF(cmyk.Cyan, cmyk.Magenta, cmyk.Yellow, cmyk.Black);
             break;
         }
         case ExtendedColor.TYPE_SEPARATION: {
             SpotColor spot = (SpotColor)value;
             SetColorStroke(spot.PdfSpotColor, spot.Tint);
             break;
         }
         case ExtendedColor.TYPE_PATTERN: {
             PatternColor pat = (PatternColor)value;
             SetPatternStroke(pat.Painter);
             break;
         }
         case ExtendedColor.TYPE_SHADING: {
             ShadingColor shading = (ShadingColor)value;
             SetShadingStroke(shading.PdfShadingPattern);
             break;
         }
         case ExtendedColor.TYPE_DEVICEN: {
             DeviceNColor devicen = (DeviceNColor) value;
             SetColorStroke(devicen.PdfDeviceNColor, devicen.Tints);
             break;
         }
         case ExtendedColor.TYPE_LAB: {
             LabColor lab = (LabColor) value;
             SetColorStroke(lab.LabColorSpace, lab.L, lab.A, lab.B);
             break;
         }
         default:
             SetRGBColorStroke(value.R, value.G, value.B);
             break;
     }
 }
Beispiel #20
0
 /// <summary>
 /// Font's color. Its default value is black.
 /// </summary>
 public void Color(System.Drawing.Color value)
 {
     _color = new BaseColor(value);
 }
 /** 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;
 }    
Beispiel #22
0
 /** Places the barcode in a <CODE>PdfContentByte</CODE>. The
  * barcode is always placed at coodinates (0, 0). Use the
  * translation matrix to move it elsewhere.<p>
  * The bars and text are written in the following colors:<p>
  * <P><TABLE BORDER=1>
  * <TR>
  *    <TH><P><CODE>barColor</CODE></TH>
  *    <TH><P><CODE>textColor</CODE></TH>
  *    <TH><P>Result</TH>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P>bars and text painted with current fill color</TD>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>barColor</CODE></TD>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P>bars and text painted with <CODE>barColor</CODE></TD>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>null</CODE></TD>
  *    <TD><P><CODE>textColor</CODE></TD>
  *    <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD>
  *    </TR>
  * <TR>
  *    <TD><P><CODE>barColor</CODE></TD>
  *    <TD><P><CODE>textColor</CODE></TD>
  *    <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD>
  *    </TR>
  * </TABLE>
  * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed
  * @param barColor the color of the bars. It can be <CODE>null</CODE>
  * @param textColor the color of the text. It can be <CODE>null</CODE>
  * @return the dimensions the barcode occupies
  */
 public abstract Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor);
 /** Sets the fill color. <CODE>color</CODE> can be an
  * <CODE>ExtendedColor</CODE>.
  * @param color the color
  */    
 public virtual void SetColorFill(BaseColor value) {
     int type = ExtendedColor.GetType(value);
     switch (type) {
         case ExtendedColor.TYPE_GRAY: {
             SetGrayFill(((GrayColor)value).Gray);
             break;
         }
         case ExtendedColor.TYPE_CMYK: {
             CMYKColor cmyk = (CMYKColor)value;
             SetCMYKColorFillF(cmyk.Cyan, cmyk.Magenta, cmyk.Yellow, cmyk.Black);
             break;
         }
         case ExtendedColor.TYPE_SEPARATION: {
             SpotColor spot = (SpotColor)value;
             SetColorFill(spot.PdfSpotColor, spot.Tint);
             break;
         }
         case ExtendedColor.TYPE_PATTERN: {
             PatternColor pat = (PatternColor)value;
             SetPatternFill(pat.Painter);
             break;
         }
         case ExtendedColor.TYPE_SHADING: {
             ShadingColor shading = (ShadingColor)value;
             SetShadingFill(shading.PdfShadingPattern);
             break;
         }
         default:
             SetRGBColorFill(value.R, value.G, value.B);
             break;
     }
 }
Beispiel #24
0
        /** Creates a template with the barcode.
         * @param cb the <CODE>PdfContentByte</CODE> to create the template. It
         * serves no other use
         * @param barColor the color of the bars. It can be <CODE>null</CODE>
         * @param textColor the color of the text. It can be <CODE>null</CODE>
         * @return the template
         * @see #placeBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor)
         */
        virtual public PdfTemplate CreateTemplateWithBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor)
        {
            PdfTemplate tp   = cb.CreateTemplate(0, 0);
            Rectangle   rect = PlaceBarcode(tp, barColor, textColor);

            tp.BoundingBox = rect;
            return(tp);
        }
 private void SaveColor(BaseColor color, bool fill) {
     if (IsTagged()) {
         if (inText) {
             if (fill) {
                 state.textColorFill = color;
             } else {
                 state.textColorStroke = color;
             }
         } else {
             if (fill) {
                 state.colorFill = color;
             } else {
                 state.colorStroke = color;
             }
         }
     }
     else {
         if (fill) {
             state.colorFill = color;
         }
         else {
             state.colorStroke = color;
         }
     }
 }
Beispiel #26
0
 /** Creates an <CODE>Image</CODE> with the barcode.
  * @param cb the <CODE>PdfContentByte</CODE> to create the <CODE>Image</CODE>. It
  * serves no other use
  * @param barColor the color of the bars. It can be <CODE>null</CODE>
  * @param textColor the color of the text. It can be <CODE>null</CODE>
  * @return the <CODE>Image</CODE>
  * @see #placeBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor)
  */
 virtual public Image CreateImageWithBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor)
 {
     return(Image.GetInstance(CreateTemplateWithBarcode(cb, barColor, textColor)));
 }
Beispiel #27
0
     // constructors
 
     /**
      * Constructs a new <CODE>PdfSpotColor</CODE>.
      *
      * @param       name        a string value
      * @param       tint        a tint value between 0 and 1
      * @param       altcs       a altnative colorspace value
      */
 
     public PdfSpotColor(string name, BaseColor altcs) {
         this.name = new PdfName(name);
         this.altcs = altcs;
     }
Beispiel #28
0
                                                                        , "C:\\WINDOWS\\FONTS\\simsun.ttc,0");//arial unicode MS是完整的unicode字型。

            public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
                                         bool cached)
            {
                BaseFont baseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                return(new Font(baseFont, size, style, color));
            }
 /** 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) {
     if (supp.Font != null)
         supp.BarHeight = ean.BarHeight + supp.Baseline - supp.Font.GetFontDescriptor(BaseFont.CAPHEIGHT, supp.Size);
     else
         supp.BarHeight = ean.BarHeight;
     Rectangle eanR = ean.BarcodeSize;
     cb.SaveState();
     ean.PlaceBarcode(cb, barColor, textColor);
     cb.RestoreState();
     cb.SaveState();
     cb.ConcatCTM(1, 0, 0, 1, eanR.Width + n, eanR.Height - ean.BarHeight);
     supp.PlaceBarcode(cb, barColor, textColor);
     cb.RestoreState();
     return this.BarcodeSize;
 }
Beispiel #30
0
        /** 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);
        }
Beispiel #31
0
 /**
  * Copy constructor.
  * @param source    another GraphicsState object
  */
 public GraphicsState(GraphicsState source){
     // note: all of the following are immutable, with the possible exception of font
     // so it is safe to copy them as-is
     ctm = source.ctm;
     characterSpacing = source.characterSpacing;
     wordSpacing = source.wordSpacing;
     horizontalScaling = source.horizontalScaling;
     leading = source.leading;
     font = source.font;
     fontSize = source.fontSize;
     renderMode = source.renderMode;
     rise = source.rise;
     knockout = source.knockout;
     colorSpaceFill = source.colorSpaceFill;
     colorSpaceStroke = source.colorSpaceStroke;
     fillColor = source.fillColor;
     strokeColor = source.strokeColor;
 }
Beispiel #32
0
        /** Places the barcode in a <CODE>PdfContentByte</CODE>. The
         * barcode is always placed at coodinates (0, 0). Use the
         * translation matrix to move it elsewhere.<p>
         * The bars and text are written in the following colors:<p>
         * <P><TABLE BORDER=1>
         * <TR>
         *    <TH><P><CODE>barColor</CODE></TH>
         *    <TH><P><CODE>textColor</CODE></TH>
         *    <TH><P>Result</TH>
         *    </TR>
         * <TR>
         *    <TD><P><CODE>null</CODE></TD>
         *    <TD><P><CODE>null</CODE></TD>
         *    <TD><P>bars and text painted with current fill color</TD>
         *    </TR>
         * <TR>
         *    <TD><P><CODE>barColor</CODE></TD>
         *    <TD><P><CODE>null</CODE></TD>
         *    <TD><P>bars and text painted with <CODE>barColor</CODE></TD>
         *    </TR>
         * <TR>
         *    <TD><P><CODE>null</CODE></TD>
         *    <TD><P><CODE>textColor</CODE></TD>
         *    <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD>
         *    </TR>
         * <TR>
         *    <TD><P><CODE>barColor</CODE></TD>
         *    <TD><P><CODE>textColor</CODE></TD>
         *    <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD>
         *    </TR>
         * </TABLE>
         * @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed
         * @param barColor the color of the bars. It can be <CODE>null</CODE>
         * @param textColor the color of the text. It can be <CODE>null</CODE>
         * @return the dimensions the barcode occupies
         */
        public override Rectangle PlaceBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor)
        {
            string fullCode = code;
            float  fontX    = 0;
            string bCode    = code;

            if (extended)
            {
                bCode = GetCode39Ex(code);
            }
            if (font != null)
            {
                if (generateChecksum && checksumText)
                {
                    fullCode += GetChecksum(bCode);
                }
                if (startStopText)
                {
                    fullCode = "*" + fullCode + "*";
                }
                fontX = font.GetWidthPoint(fullCode = altText != null ? altText : fullCode, size);
            }
            if (generateChecksum)
            {
                bCode += GetChecksum(bCode);
            }
            int   len        = bCode.Length + 2;
            float fullWidth  = len * (6 * x + 3 * x * n) + (len - 1) * x;
            float barStartX  = 0;
            float textStartX = 0;

            switch (textAlignment)
            {
            case Element.ALIGN_LEFT:
                break;

            case Element.ALIGN_RIGHT:
                if (fontX > fullWidth)
                {
                    barStartX = fontX - fullWidth;
                }
                else
                {
                    textStartX = fullWidth - fontX;
                }
                break;

            default:
                if (fontX > fullWidth)
                {
                    barStartX = (fontX - fullWidth) / 2;
                }
                else
                {
                    textStartX = (fullWidth - fontX) / 2;
                }
                break;
            }
            float barStartY  = 0;
            float textStartY = 0;

            if (font != null)
            {
                if (baseline <= 0)
                {
                    textStartY = barHeight - baseline;
                }
                else
                {
                    textStartY = -font.GetFontDescriptor(BaseFont.DESCENT, size);
                    barStartY  = textStartY + baseline;
                }
            }
            byte[] bars  = GetBarsCode39(bCode);
            bool   print = true;

            if (barColor != null)
            {
                cb.SetColorFill(barColor);
            }
            for (int k = 0; k < bars.Length; ++k)
            {
                float w = (bars[k] == 0 ? x : x * n);
                if (print)
                {
                    cb.Rectangle(barStartX, barStartY, w - inkSpreading, barHeight);
                }
                print      = !print;
                barStartX += w;
            }
            cb.Fill();
            if (font != null)
            {
                if (textColor != null)
                {
                    cb.SetColorFill(textColor);
                }
                cb.BeginText();
                cb.SetFontAndSize(font, size);
                cb.SetTextMatrix(textStartX, textStartY);
                cb.ShowText(fullCode);
                cb.EndText();
            }
            return(this.BarcodeSize);
        }
Beispiel #33
0
 private void SetColorAttribute(BaseColor newColor, PdfObject oldColor, PdfName attributeName)
 {
     float[] colorArr = new float[] {newColor.R/255f, newColor.G/255f, newColor.B/255f};
     if ((oldColor != null) && (oldColor is PdfArray))
     {
         PdfArray oldC = (PdfArray) oldColor;
         if (ColorsEqual(oldC, colorArr))
             this.SetAttribute(attributeName, new PdfArray(colorArr));
         else
             this.SetAttribute(attributeName, new PdfArray(colorArr));
     }
     else
         this.SetAttribute(attributeName, new PdfArray(colorArr));
 }
Beispiel #34
0
        public void ReadAll()
        {
            if (meta.ReadInt() != unchecked ((int)0x9AC6CDD7))
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("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;
                    }
                    List <float[]> ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2);
                    if (ar.Count == 0)
                    {
                        break;
                    }
                    float[] pt = ar[0];
                    cb.MoveTo(cx, cy);
                    cb.LineTo(pt[0], pt[1]);
                    for (int k = 0; k < ar.Count; ++k)
                    {
                        pt = 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;
                    }
                    List <float[]> ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2);
                    if (ar.Count == 0)
                    {
                        break;
                    }
                    float[] pt = ar[0];
                    cx = pt[0];
                    cy = pt[1];
                    cb.MoveTo(cx, cy);
                    for (int k = 0; k < ar.Count; ++k)
                    {
                        pt = 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:
                {
                    BaseColor 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);
        }
Beispiel #35
0
 internal GraphicState(GraphicState cp) {
     fontDetails = cp.fontDetails;
     colorDetails = cp.colorDetails;
     size = cp.size;
     xTLM = cp.xTLM;
     yTLM = cp.yTLM;
     aTLM = cp.aTLM;
     bTLM = cp.bTLM;
     cTLM = cp.cTLM;
     dTLM = cp.dTLM;
     tx = cp.tx;
     leading = cp.leading;
     scale = cp.scale;
     charSpace = cp.charSpace;
     wordSpace = cp.wordSpace;
     textColorFill = cp.textColorFill;
     graphicsColorFill = cp.graphicsColorFill;
     textColorStroke = cp.textColorStroke;
     graphicsColorStroke = cp.graphicsColorStroke;
 }
Beispiel #36
0
        //--------------------------------------------------------------------------------------------------
        void MarkText(List <TextItem> items, int iPosition, int iCount, PdfStamper stamper, BaseColor color, int iPageAdd = 0, string stComment = null)
        {
            const string stTittle = "PDFCompare";

            if (iCount == 0)
            {
                float rWidth, rPosition;
                if (iPosition >= items.Count)
                {
                    iPosition = items.Count - 1;
                    rWidth    = (items[iPosition].MaxY - items[iPosition].MinY) / 5;
                    rPosition = items[iPosition].MaxX;
                }
                else
                {
                    rWidth    = (items[iPosition].MaxY - items[iPosition].MinY) / 5;
                    rPosition = items[iPosition].MinX - rWidth;
                }
                Rectangle     rect      = new Rectangle(rPosition, items[iPosition].MaxY, rPosition + rWidth, items[iPosition].MinY);
                float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                highlight.Color = color;
                highlight.Title = stTittle;
                stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
            }
            else
            {
                while (iCount > 0 && items[iPosition].IsImage)
                {
                    TextItem  item       = items[iPosition];
                    Rectangle rect       = new Rectangle(item.MinX, item.MaxY, item.MaxX, item.MinY);
                    PdfArray  vertices   = new PdfArray();
                    float     rHalfWidth = 4;
                    vertices.Add(new PdfNumber(item.MinX - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinY - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxX + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinY - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxX + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxY + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinX - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MaxY + rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinX - rHalfWidth));
                    vertices.Add(new PdfNumber(item.MinY - rHalfWidth));
                    PdfAnnotation highlight = PdfAnnotation.CreatePolygonPolyline(stamper.Writer, rect, stComment, true, vertices);
                    highlight.Color  = color;
                    highlight.Title  = stTittle;
                    highlight.Border = new PdfBorderArray(0, 0, rHalfWidth * 2);
                    stamper.AddAnnotation(highlight, item.Page + iPageAdd);
                    iPosition++;
                    iCount--;
                }
                if (iCount == 0)
                {
                    return;
                }
                int i;
                for (i = iPosition; i < iPosition + iCount; i++)
                {
                    if (items[i].IsImage)
                    {
                        MarkText(items, iPosition, i - iPosition, stamper, color, iPageAdd, stComment);
                        MarkText(items, i, 1, stamper, color, iPageAdd, stComment);
                        if (i + 1 >= iPosition + iCount)
                        {
                            return;
                        }
                        iCount   -= (i - iPosition) + 1;
                        iPosition = i + 1;
                    }
                }
                if (!items[iPosition].IsNewLine)
                {
                    i = iPosition;
                    while (i < iPosition + iCount - 1 && !items[i + 1].IsNewLine)
                    {
                        i++;
                    }
                    Rectangle     rect      = new Rectangle(items[iPosition].MinX, items[iPosition].MaxY, items[i].MaxX, items[iPosition].MinY);
                    float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                    PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                    highlight.Color = color;
                    highlight.Title = stTittle;
                    stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
                    iCount   -= (i - iPosition) + 1;
                    iPosition = i + 1;
                }
                if (iCount == 0)
                {
                    return;
                }
                if (items.Count > iPosition + iCount && !items[iPosition + iCount].IsNewLine)
                {
                    i = iPosition + iCount - 1;
                    while (!items[i].IsNewLine)
                    {
                        i--;
                    }
                    Rectangle     rect      = new Rectangle(items[i].MinX, items[i].MaxY, items[i = iPosition + iCount - 1].MaxX, items[i].MinY);
                    float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                    PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                    highlight.Color = color;
                    highlight.Title = stTittle;
                    stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
                    iCount -= iPosition + iCount - i;
                }
                if (iCount == 0)
                {
                    return;
                }
                i = iPosition;
                float rMinX = items[iPosition].MinX;
                float rMaxX = items[iPosition].MaxX;
                while (i < iPosition + iCount)
                {
                    i++;
                    if (i == iPosition + iCount || items[iPosition].Page != items[i].Page)
                    {
                        Rectangle     rect      = new Rectangle(rMinX, items[iPosition].MaxY, rMaxX, items[i - 1].MinY);
                        float[]       quad      = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                        PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                        highlight.Color = color;
                        highlight.Title = stTittle;
                        stamper.AddAnnotation(highlight, items[iPosition].Page + iPageAdd);
                        iCount   -= i - iPosition;
                        iPosition = i;
                        if (iCount == 0)
                        {
                            return;
                        }
                        rMinX = items[iPosition].MinX;
                        rMaxX = items[iPosition].MaxX;
                    }
                    if (items[i].MinX < rMinX)
                    {
                        rMinX = items[i].MinX;
                    }
                    if (items[i].MaxX > rMaxX)
                    {
                        rMaxX = items[i].MaxX;
                    }
                }

                /*
                 * for(i = iPosition; i < iPosition + iCount; i++)
                 * {
                 *      TextItem item = items[i];
                 *      Rectangle rect = new Rectangle(item.MinX, item.MaxY, item.MaxX, item.MinY);
                 *      float[] quad = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
                 *      PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, stComment, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
                 *      highlight.Color = color;
                 *      highlight.Title = stTittle;
                 *      stamper.AddAnnotation(highlight, item.Page + iPageAdd);
                 * }
                 */
            }
        }
Beispiel #37
0
 /** 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) {
     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;
 }
Beispiel #38
0
        //--------------------------------------------------------------------------------------------------
        public int Compare(string stPDF1, string stPDF2, string stPDFResult)
        {
            int i;

            try
            {
                PdfReader reader1 = new PdfReader(stPDF1);
                reader1.ConsolidateNamedDestinations();
                //ExtractionStrategy strategy = new ExtractionStrategy();
                LocationExtractionStrategy strategy = new LocationExtractionStrategy();
                for (i = 1; i <= reader1.NumberOfPages; i++)
                {
                    strategy.Page = i;
                    PdfTextExtractor.GetTextFromPage(reader1, i, strategy);
                }
                List <TextItem> items1 = strategy.GetTextItems();
                strategy.Reset();
                PdfReader reader2 = new PdfReader(stPDF2);
                reader2.ConsolidateNamedDestinations();
                for (i = 1; i <= reader2.NumberOfPages; i++)
                {
                    strategy.Page = i;
                    PdfTextExtractor.GetTextFromPage(reader2, i, strategy);
                }
                List <TextItem> items2 = strategy.GetTextItems();
                //...
                StringBuilder sb1 = new StringBuilder();
                for (i = 0; i < items1.Count; i++)
                {
                    if (i != 0)
                    {
                        sb1.Append('\n');
                    }
                    sb1.Append(items1[i].Text);
                }
                StringBuilder sb2 = new StringBuilder();
                for (i = 0; i < items2.Count; i++)
                {
                    if (i != 0)
                    {
                        sb2.Append('\n');
                    }
                    sb2.Append(items2[i].Text);
                }
                Diff        diff      = new Diff();
                Diff.Item[] diffitems = diff.DiffText(sb1.ToString(), sb2.ToString());
                //...
                MemoryStream ms1 = new MemoryStream();
                MemoryStream ms2 = new MemoryStream();
                using (PdfStamper stamper1 = new PdfStamper(reader1, ms1, '\0', true))
                {
                    using (PdfStamper stamper2 = new PdfStamper(reader2, ms2, '\0', true))
                    {
                        AddHeader(stamper1, reader1, string.Format("Отличий обнаружено: {0}", diffitems.Length));
                        //...
                        int iPageAdded1 = 0;
                        int iPageAdded2 = 0;
                        for (i = 0; i < diffitems.Length; i++)
                        {
                            Diff.Item diffitem  = diffitems[i];
                            int       iColor    = diffitem.deletedA == 0 ? Settings.ColorAdded : (diffitem.insertedB == 0 ? Settings.ColorDeleted : Settings.ColorChanged);
                            BaseColor color     = new BaseColor(iColor & 0x000000FF, (iColor & 0x0000FF00) >> 8, (iColor & 0x00FF0000) >> 16);
                            string    stComment = string.Format("Отличие {0} из {1}", i + 1, diffitems.Length);
                            MarkText(items1, diffitem.StartA, diffitem.deletedA, stamper1, color, iPageAdded1, stComment);
                            MarkText(items2, diffitem.StartB, diffitem.insertedB, stamper2, color, iPageAdded2, stComment);
                            // Если фрагменты начинаются на разных страницах, то выравниваем
                            while (IntexOrLast(items1, diffitem.StartA).Page + iPageAdded1 < IntexOrLast(items2, diffitem.StartB).Page + iPageAdded2)
                            {
                                if ((IntexOrLast(items2, diffitem.StartB).Page + iPageAdded2) - (IntexOrLast(items1, diffitem.StartA).Page + iPageAdded1) == 1)
                                {
                                    Rectangle rectPage1 = reader1.GetPageSizeWithRotation(IntexOrLast(items1, diffitem.StartA).Page + iPageAdded1);
                                    Rectangle rectPage2 = reader2.GetPageSizeWithRotation(IntexOrLast(items2, diffitem.StartB).Page + iPageAdded2);
                                    if (INSERT_PAGE_FACTOR > IntexOrLast(items1, diffitem.StartA).MaxY / rectPage1.Height + ((rectPage2.Height - IntexOrLast(items2, diffitem.StartB).MaxY)) / rectPage2.Height)
                                    {
                                        break;
                                    }
                                }
                                int iNewPage = IntexOrLast(items1, diffitem.StartA).Page;
                                if (iNewPage == reader1.NumberOfPages)
                                {
                                    iNewPage++;
                                }
                                InsertPage(stamper1, iNewPage, reader1.GetPageSizeWithRotation(IntexOrLast(items1, diffitem.StartA).Page + iPageAdded1));
                                iPageAdded1++;
                            }
                            while (IntexOrLast(items1, diffitem.StartA).Page + iPageAdded1 > IntexOrLast(items2, diffitem.StartB).Page + iPageAdded2)
                            {
                                if ((IntexOrLast(items1, diffitem.StartA).Page + iPageAdded1) - (IntexOrLast(items2, diffitem.StartB).Page + iPageAdded2) == 1)
                                {
                                    Rectangle rectPage1 = reader1.GetPageSizeWithRotation(IntexOrLast(items1, diffitem.StartA).Page + iPageAdded1);
                                    Rectangle rectPage2 = reader2.GetPageSizeWithRotation(IntexOrLast(items2, diffitem.StartB).Page + iPageAdded2);
                                    if (INSERT_PAGE_FACTOR > ((rectPage1.Height - IntexOrLast(items1, diffitem.StartA).MaxY) / rectPage1.Height) + IntexOrLast(items2, diffitem.StartB).MaxY / rectPage2.Height)
                                    {
                                        break;
                                    }
                                }
                                int iNewPage = IntexOrLast(items2, diffitem.StartB).Page;
                                if (iNewPage == reader2.NumberOfPages)
                                {
                                    iNewPage++;
                                }
                                InsertPage(stamper2, IntexOrLast(items2, diffitem.StartB).Page, reader2.GetPageSizeWithRotation(IntexOrLast(items2, diffitem.StartB).Page + iPageAdded2));
                                iPageAdded2++;
                            }
                        }
                        // Выравниваем количество страниц
                        while (reader1.NumberOfPages < reader2.NumberOfPages)
                        {
                            InsertPage(stamper1, reader1.NumberOfPages + 1, reader1.GetPageSizeWithRotation(reader1.NumberOfPages - 1));
                        }
                        while (reader1.NumberOfPages > reader2.NumberOfPages)
                        {
                            InsertPage(stamper2, reader2.NumberOfPages + 1, reader2.GetPageSizeWithRotation(reader2.NumberOfPages - 1));
                        }
                    }
                }
                reader1 = new PdfReader(ms1.ToArray());
                reader2 = new PdfReader(ms2.ToArray());
                //...
                using (FileStream stream = new FileStream(stPDFResult, FileMode.Create))
                {
                    Document document = new Document();
                    PdfCopy  pdf      = new PdfCopy(document, stream);
                    document.Open();
                    for (i = 1; i <= reader1.NumberOfPages; i++)
                    {
                        PdfImportedPage page = pdf.GetImportedPage(reader1, i);
                        pdf.AddPage(page);
                        page = pdf.GetImportedPage(reader2, i);
                        pdf.AddPage(page);
                    }
                    reader1.Close();
                    reader2.Close();
                    document.Close();
                }
            }
            catch (Exception /*e*/)
            {
                return(1);
            }
            return(0);
        }
 virtual public void PlaceBarcode(PdfContentByte cb, BaseColor foreground, float moduleHeight, float moduleWidth) {
     int w = width + 2*ws;
     int h = height + 2*ws;
     int stride = (w + 7)/8;
     int ptr = 0;
     cb.SetColorFill(foreground);
     for (int k = 0; k < h; ++k) {
         int p = k*stride;
         for (int j = 0; j < w; ++j) {
             int b = image[p + j/8] & 0xff;
             b <<= j%8;
             if ((b & 0x80) != 0) {
                 cb.Rectangle(j*moduleWidth, (h - k - 1)*moduleHeight, moduleWidth, moduleHeight);
             }
         }
     }
     cb.Fill();
 }
        public static Image CreateRectangle(PdfWriter writer, float x, float y, float width, float height, BaseColor backColor)
        {
            PdfTemplate template = writer.DirectContent.CreateTemplate(width, height);

            template.SetColorFill(backColor);
            template.Rectangle(x, y, width, height);
            template.Fill();
            writer.ReleaseTemplate(template);

            return(Image.GetInstance(template));
        }
Beispiel #41
0
 virtual public void Init(InputMeta meta) {
     style = meta.ReadWord();
     penWidth = meta.ReadShort();
     meta.ReadWord();
     color = meta.ReadColor();
 }
Beispiel #42
0
        protected PdfPCell getNewCell(string Texto, Font Fonte, int Alinhamento, float Espacamento, int Borda, BaseColor CorBorda, BaseColor CorFundo)
        {
            var cell = new PdfPCell(new Phrase(Texto, Fonte));

            cell.HorizontalAlignment = Alinhamento;
            cell.Padding             = Espacamento;
            cell.Border          = Borda;
            cell.BorderColor     = CorBorda;
            cell.BackgroundColor = CorFundo;

            return(cell);
        }
 internal void CopyParameters(GraphicState cp) {
     fontDetails = cp.fontDetails;
     colorDetails = cp.colorDetails;
     size = cp.size;
     xTLM = cp.xTLM;
     yTLM = cp.yTLM;
     aTLM = cp.aTLM;
     bTLM = cp.bTLM;
     cTLM = cp.cTLM;
     dTLM = cp.dTLM;
     tx = cp.tx;
     leading = cp.leading;
     scale = cp.scale;
     charSpace = cp.charSpace;
     wordSpace = cp.wordSpace;
     textColorFill = cp.textColorFill;
     colorFill = cp.colorFill;
     textColorStroke = cp.textColorStroke;
     colorStroke = cp.colorStroke;
     CTM = (AffineTransform)cp.CTM.Clone();
     textRenderMode = cp.textRenderMode;
     extGState = cp.extGState;
 }
Beispiel #44
0
 protected PdfPCell getNewCell(string Texto, Font Fonte, int Alinhamento, float Espacamento, int Borda, BaseColor CorBorda)
 {
     return(getNewCell(Texto, Fonte, Alinhamento, Espacamento, Borda, CorBorda, new BaseColor(255, 255, 255)));
 }
 /**
  * Create a new uncolored tiling pattern.
  * Variables xstep and ystep are set to the same values
  * of width and height.
  * @param width the width of the pattern
  * @param height the height of the pattern
  * @param color the default color. Can be <CODE>null</CODE>
  * @return the <CODE>PdfPatternPainter</CODE> where the pattern will be created
  */
 public PdfPatternPainter CreatePattern(float width, float height, BaseColor color) {
     return CreatePattern(width, height, width, height, color);
 }
Beispiel #46
0
        private void ImprimeRodape(PdfWriter writer, Document doc)
        {
            #region Dados do Rodapé
            if (ImprimirRodapePadrao)
            {
                BaseColor preto   = new BaseColor(0, 0, 0);
                Font      font    = FontFactory.GetFont("Verdana", 8, Font.NORMAL, preto);
                Font      negrito = FontFactory.GetFont("Verdana", 8, Font.BOLD, preto);
                float[]   sizes   = new float[] { 1.0f, 3.5f, 1f };

                PdfPTable table = new PdfPTable(3);
                table.TotalWidth    = doc.PageSize.Width - (doc.LeftMargin + doc.RightMargin);
                table.SpacingBefore = 20f;
                table.SetWidths(sizes);

                #region Coluna TNE
                Image foot = Image.GetInstance(BasePath + @"\Content\skoll2.png");
                foot.ScalePercent(20);

                PdfPCell cell = new PdfPCell(foot);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border         = 0;
                cell.BorderWidthTop = 1.5f;
                cell.PaddingLeft    = 10f;
                cell.PaddingTop     = 10f;
                table.AddCell(cell);

                PdfPTable micros = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase("SKOLL", negrito));
                cell.Border = 0;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Sistema de Gerenciamento", font));
                cell.Border = 0;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Relatório gerado em PDF", font));
                cell.Border = 0;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border         = 0;
                cell.BorderWidthTop = 1.5f;
                cell.PaddingTop     = 10f;
                table.AddCell(cell);
                #endregion

                #region Página
                micros      = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase(DateTime.Today.ToString("dd/MM/yyyy"), font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase(DateTime.Now.ToString("HH:mm:ss"), font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border         = 0;
                cell.BorderWidthTop = 1.5f;
                cell.PaddingTop     = 10f;
                table.AddCell(cell);
                #endregion

                table.WriteSelectedRows(0, -1, doc.LeftMargin, 70, writer.DirectContent);
            }
            #endregion
        }
 /** Outputs the color values to the content.
  * @param color The color
  * @param tint the tint if it is a spot color, ignored otherwise
  */    
 internal void OutputColorNumbers(BaseColor color, float tint) {
     PdfWriter.CheckPdfIsoConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, color);
     int type = ExtendedColor.GetType(color);
     switch (type) {
         case ExtendedColor.TYPE_RGB:
             content.Append((float)(color.R) / 0xFF);
             content.Append(' ');
             content.Append((float)(color.G) / 0xFF);
             content.Append(' ');
             content.Append((float)(color.B) / 0xFF);
             break;
         case ExtendedColor.TYPE_GRAY:
             content.Append(((GrayColor)color).Gray);
             break;
         case ExtendedColor.TYPE_CMYK: {
             CMYKColor cmyk = (CMYKColor)color;
             content.Append(cmyk.Cyan).Append(' ').Append(cmyk.Magenta);
             content.Append(' ').Append(cmyk.Yellow).Append(' ').Append(cmyk.Black);
             break;
         }
         case ExtendedColor.TYPE_SEPARATION:
             content.Append(tint);
             break;
         default:
             throw new Exception(MessageLocalization.GetComposedMessage("invalid.color.type"));
     }
 }
Beispiel #48
0
        private void ImprimeCabecalho(PdfWriter writer, Document doc)
        {
            #region Dados do Cabeçalho
            if (ImprimirCabecalhoPadrao)
            {
                BaseColor preto  = new BaseColor(0, 0, 0);
                Font      font   = FontFactory.GetFont("Verdana", 8, Font.NORMAL, preto);
                Font      titulo = FontFactory.GetFont("Verdana", 12, Font.BOLD, preto);
                float[]   sizes  = new float[] { 1f, 3f, 1f };

                PdfPTable table = new PdfPTable(3);
                table.TotalWidth = doc.PageSize.Width - (doc.LeftMargin + doc.RightMargin);
                table.SetWidths(sizes);

                #region Logo Empresa
                Image foot;
                foot = Image.GetInstance(BasePath + @"\Content\skoll2.png");

                foot.ScalePercent(20);

                PdfPCell cell = new PdfPCell(foot);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.Border            = 0;
                cell.BorderWidthTop    = 1.5f;
                cell.BorderWidthBottom = 1.5f;
                cell.PaddingTop        = 10f;
                cell.PaddingBottom     = 10f;
                table.AddCell(cell);

                PdfPTable micros = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase(PageSubTitle, font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase(PageTitle, titulo));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border            = 0;
                cell.BorderWidthTop    = 1.5f;
                cell.BorderWidthBottom = 1.5f;
                cell.PaddingTop        = 10f;
                table.AddCell(cell);
                #endregion

                #region Página
                micros      = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase("Página: " + (doc.PageNumber).ToString(), font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border            = 0;
                cell.BorderWidthTop    = 1.5f;
                cell.BorderWidthBottom = 1.5f;
                cell.PaddingTop        = 10f;
                table.AddCell(cell);
                #endregion

                table.WriteSelectedRows(0, -1, doc.LeftMargin, (doc.PageSize.Height - 10), writer.DirectContent);
            }
            #endregion
        }
 /** Sets the stroke color to an uncolored pattern.
  * @param p the pattern
  * @param color the color of the pattern
  * @param tint the tint if the color is a spot color, ignored otherwise
  */    
 public virtual void SetPatternStroke(PdfPatternPainter p, BaseColor color, float tint) {
     CheckWriter();
     if (!p.IsStencil())
         throw new Exception(MessageLocalization.GetComposedMessage("an.uncolored.pattern.was.expected"));
     PageResources prs = PageResources;
     PdfName name = writer.AddSimplePattern(p);
     name = prs.AddPattern(name, p.IndirectReference);
     ColorDetails csDetail = writer.AddSimplePatternColorspace(color);
     PdfName cName = prs.AddColor(csDetail.ColorName, csDetail.IndirectReference);
     SaveColor(new UncoloredPattern(p, color, tint), false);
     content.Append(cName.GetBytes()).Append(" CS").Append_i(separator);
     OutputColorNumbers(color, tint);
     content.Append(' ').Append(name.GetBytes()).Append(" SCN").Append_i(separator);
 }
Beispiel #50
0
        public virtual PdfObject GetPdfObject(PdfWriter writer)
        {
            PdfArray array = new PdfArray(PdfName.DEVICEN);

            PdfArray colorants = new PdfArray();

            float[]       colorantsRanges = new float[spotColors.Length * 2];
            PdfDictionary colorantsDict   = new PdfDictionary();
            String        psFunFooter     = "";

            int numberOfColorants = spotColors.Length;

            float[,] CMYK = new float[4, numberOfColorants];
            int i = 0;

            for (; i < numberOfColorants; i++)
            {
                PdfSpotColor spotColorant = spotColors[i];
                colorantsRanges[2 * i]     = 0;
                colorantsRanges[2 * i + 1] = 1;
                colorants.Add(spotColorant.Name);
                if (colorantsDict.Get(spotColorant.Name) != null)
                {
                    throw new Exception(MessageLocalization.GetComposedMessage("devicen.component.names.shall.be.different"));
                }
                if (colorantsDetails != null)
                {
                    colorantsDict.Put(spotColorant.Name, colorantsDetails[i].IndirectReference);
                }
                else
                {
                    colorantsDict.Put(spotColorant.Name, spotColorant.GetPdfObject(writer));
                }
                BaseColor color = spotColorant.AlternativeCS;
                if (color is ExtendedColor)
                {
                    int type = ((ExtendedColor)color).Type;
                    switch (type)
                    {
                    case ExtendedColor.TYPE_GRAY:
                        CMYK[0, i] = 0;
                        CMYK[1, i] = 0;
                        CMYK[2, i] = 0;
                        CMYK[3, i] = 1 - ((GrayColor)color).Gray;
                        break;

                    case ExtendedColor.TYPE_CMYK:
                        CMYK[0, i] = ((CMYKColor)color).Cyan;
                        CMYK[1, i] = ((CMYKColor)color).Magenta;
                        CMYK[2, i] = ((CMYKColor)color).Yellow;
                        CMYK[3, i] = ((CMYKColor)color).Black;
                        break;

                    case ExtendedColor.TYPE_LAB:
                        CMYKColor cmyk = ((LabColor)color).ToCmyk();
                        CMYK[0, i] = cmyk.Cyan;
                        CMYK[1, i] = cmyk.Magenta;
                        CMYK[2, i] = cmyk.Yellow;
                        CMYK[3, i] = cmyk.Black;
                        break;

                    default:
                        throw new Exception(
                                  MessageLocalization.GetComposedMessage(
                                      "only.rgb.gray.and.cmyk.are.supported.as.alternative.color.spaces"));
                    }
                }
                else
                {
                    float r = color.R;
                    float g = color.G;
                    float b = color.B;
                    float computedC = 0, computedM = 0, computedY = 0, computedK = 0;

                    // BLACK
                    if (r == 0 && g == 0 && b == 0)
                    {
                        computedK = 1;
                    }
                    else
                    {
                        computedC = 1 - (r / 255);
                        computedM = 1 - (g / 255);
                        computedY = 1 - (b / 255);

                        float minCMY = Math.Min(computedC,
                                                Math.Min(computedM, computedY));
                        computedC = (computedC - minCMY) / (1 - minCMY);
                        computedM = (computedM - minCMY) / (1 - minCMY);
                        computedY = (computedY - minCMY) / (1 - minCMY);
                        computedK = minCMY;
                    }
                    CMYK[0, i] = computedC;
                    CMYK[1, i] = computedM;
                    CMYK[2, i] = computedY;
                    CMYK[3, i] = computedK;
                }
                psFunFooter += "pop ";
            }
            array.Add(colorants);

            String psFunHeader = String.Format(NumberFormatInfo.InvariantInfo, "1.000000 {0} 1 roll ", numberOfColorants + 1);

            array.Add(PdfName.DEVICECMYK);
            psFunHeader = psFunHeader + psFunHeader + psFunHeader + psFunHeader;
            String psFun = "";

            i = numberOfColorants + 4;
            for (; i > numberOfColorants; i--)
            {
                psFun += String.Format(NumberFormatInfo.InvariantInfo, "{0} -1 roll ", i);
                for (int j = numberOfColorants; j > 0; j--)
                {
                    psFun += String.Format(NumberFormatInfo.InvariantInfo, "{0} index {1} mul 1.000000 cvr exch sub mul ", j,
                                           CMYK[numberOfColorants + 4 - i, numberOfColorants - j]);
                }
                psFun += String.Format(NumberFormatInfo.InvariantInfo, "1.000000 cvr exch sub {0} 1 roll ", i);
            }

            PdfFunction func = PdfFunction.Type4(writer, colorantsRanges, new float[] { 0, 1, 0, 1, 0, 1, 0, 1 },
                                                 "{ " + psFunHeader + psFun + psFunFooter + "}");

            array.Add(func.Reference);

            PdfDictionary attr = new PdfDictionary();

            attr.Put(PdfName.SUBTYPE, PdfName.NCHANNEL);
            attr.Put(PdfName.COLORANTS, colorantsDict);
            array.Add(attr);

            return(array);
        }
 private void RestoreColor(BaseColor color, bool fill) {
     if (IsTagged()) {
         if (color is UncoloredPattern) {
             UncoloredPattern c = (UncoloredPattern)color;
             if (fill)
                 SetPatternFill(c.Painter, c.color, c.tint);
             else
                 SetPatternStroke(c.Painter, c.color, c.tint);
         } else {
             if (fill)
                 SetColorFill(color);
             else
                 SetColorStroke(color);
         }
     }
 }
Beispiel #52
0
        public void GenerateAdditionalexam(string filePDF, OrganizationDto MedicalCenter, PacientList DatosPaciente, UsuarioGrabo usuarioGraba, string MotivoComentario, List <Categoria> DataSource, List <AdditionalExamCustom> ListAdditional)
        {
            Document document = new Document(PageSize.A5, 20f, 20f, 20f, 20f);

            document.SetPageSize(iTextSharp.text.PageSize.A5);

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePDF, FileMode.Create));
            pdfPage   page   = new pdfPage();

            writer.PageEvent = page;
            document.Open();

            #region Declaration Tables
            var             subTitleBackGroundColor = new BaseColor(System.Drawing.Color.Gray);
            string          include      = string.Empty;
            List <PdfPCell> cells        = null;
            float[]         columnWidths = null;
            PdfPTable       header2      = new PdfPTable(6);
            header2.HorizontalAlignment = Element.ALIGN_CENTER;
            header2.WidthPercentage     = 100;
            float[] widths1 = new float[] { 16.6f, 18.6f, 16.6f, 16.6f, 16.6f, 16.6f };
            header2.SetWidths(widths1);
            PdfPTable companyData = new PdfPTable(6);
            companyData.HorizontalAlignment = Element.ALIGN_CENTER;
            companyData.WidthPercentage     = 100;
            float[] widthscolumnsCompanyData = new float[] { 16.6f, 16.6f, 16.6f, 16.6f, 16.6f, 16.6f };
            companyData.SetWidths(widthscolumnsCompanyData);
            PdfPTable filiationWorker = new PdfPTable(4);
            PdfPTable table           = null;
            PdfPCell  cell            = null;
            document.Add(new Paragraph("\r\n"));
            #endregion

            #region Fonts
            Font fontTitle1               = FontFactory.GetFont("Calibri", 10, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontTitle2               = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
            Font fontTitle2_              = FontFactory.GetFont("Calibri", 6, Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
            Font fontTitleTable           = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontTitleTableNegro      = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.UNDERLINE, new BaseColor(System.Drawing.Color.Black));
            Font fontSubTitle             = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.White));
            Font fontSubTitleNegroNegrita = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));

            Font fontColumnValue         = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
            Font fontColumnValueBold     = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontColumnValueApendice = FontFactory.GetFont("Calibri", 5, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));

            Font fontTitleTableAntecedentesOcupacionales  = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontColumnValueAntecedentesOcupacionales = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
            #endregion


            #region CABECERA
            cells = new List <PdfPCell>();
            var pdfCell = new PdfPCell();

            if (MedicalCenter.b_Image != null)
            {
                iTextSharp.text.Image imagenEmpresa = iTextSharp.text.Image.GetInstance(HandlingItextSharp.GetImage(MedicalCenter.b_Image));
                imagenEmpresa.ScalePercent(25);

                //imagenEmpresa.SetAbsolutePosition(40, 790);
                //document.Add(imagenEmpresa);
                pdfCell = new PdfPCell(imagenEmpresa)
                {
                    Colspan = 1, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, UseVariableBorders = true, BorderColor = BaseColor.WHITE
                };
            }
            else
            {
                pdfCell = new PdfPCell(new Phrase("SIN LOGOTIPO", fontTitle2_))
                {
                    Colspan = 1, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, BorderColor = BaseColor.WHITE
                };
            }

            var names = new List <PdfPCell>()
            {
                pdfCell,
                new PdfPCell(new Phrase(MedicalCenter.v_Name, fontTitle2_))
                {
                    Colspan = 1, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, UseVariableBorders = true, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(MedicalCenter.v_Address, fontTitle2_))
                {
                    Colspan = 2, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, UseVariableBorders = true, BorderColor = BaseColor.WHITE
                },
            };

            columnWidths = new float[] { 30f, 70f };
            table        = HandlingItextSharp.GenerateTableFromCells(names, columnWidths, null, fontTitleTable);
            document.Add(table);

            var cellsTit = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("\nORDEN DE EXÁMENES MÉDICOS \nADICIONALES", fontTitle1))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, BorderColor = BaseColor.WHITE
                },
            };
            columnWidths = new float[] { 100f };
            table        = HandlingItextSharp.GenerateTableFromCells(cellsTit, columnWidths, null, fontTitleTable);
            document.Add(table);

            string PacientFullName = "", Edad = "", FechaNac = "", TipoDoc = "", DocNumber = "", Direccion = "", Cargo = "", nHistoria = "---", Celular = "";

            if (DatosPaciente != null)
            {
                PacientFullName = DatosPaciente.v_FirstLastName + " " + DatosPaciente.v_SecondLastName + " " + DatosPaciente.v_FirstName;
                Edad            = DatosPaciente.Edad.ToString();
                FechaNac        = DatosPaciente.d_Birthdate.Value.ToShortDateString();
                DocNumber       = DatosPaciente.v_DocNumber == null ? "---" : DatosPaciente.v_DocNumber;
                Direccion       = string.IsNullOrEmpty(DatosPaciente.v_AdressLocation) ? "---" : DatosPaciente.v_AdressLocation;
                Cargo           = string.IsNullOrEmpty(DatosPaciente.v_CurrentOccupation) ? "---" : DatosPaciente.v_CurrentOccupation;
                Celular         = string.IsNullOrEmpty(DatosPaciente.v_TelephoneNumber) ? "---" : DatosPaciente.v_TelephoneNumber;
                if (DatosPaciente.i_DocTypeId == 1)
                {
                    TipoDoc = "DNI";
                }
                else if (DatosPaciente.i_DocTypeId == 2)
                {
                    TipoDoc = "Pasaporte";
                }
                else if (DatosPaciente.i_DocTypeId == 3)
                {
                    TipoDoc = "Licencia de Conducir";
                }
                else if (DatosPaciente.i_DocTypeId == 4)
                {
                    TipoDoc = "Carnet de Extranjeria";
                }
            }

            //Datos del paciente
            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("NOMBRES:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(PacientFullName, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("EDAD:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(Edad, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("F. NAC:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(FechaNac, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },

                new PdfPCell(new Phrase(TipoDoc + ":", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(DocNumber, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("DIRECCIÓN:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(Direccion, fontColumnValue))
                {
                    Colspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("CARGO:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(Cargo, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("N° HISTORIA:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("CSL-" + DocNumber, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("CELULAR:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase(Celular, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
            };
            columnWidths = new float[] { 12f, 27f, 15f, 23f, 12f, 11f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);


            #endregion

            #region CUERPO
            //resumen

            var pdfCellComentario = new PdfPCell();
            if (MotivoComentario.Length > 0)
            {
                pdfCellComentario = new PdfPCell(new Phrase(MotivoComentario, fontColumnValue))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT,
                    VerticalAlignment   = iTextSharp.text.Element.ALIGN_MIDDLE,
                    MinimumHeight       = 30f,
                    BorderColor         = BaseColor.WHITE
                };
            }
            else
            {
                pdfCellComentario = new PdfPCell(new Phrase("........................................................................................................................................................................ \n........................................................................................................................................................................", fontColumnValue))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, BorderColor = BaseColor.WHITE
                };
            }
            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("RESUMEN", fontTitleTableNegro))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
                pdfCellComentario,
            };
            columnWidths = new float[] { 100f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);


            //exámenes
            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("EXÁMENES", fontTitleTableNegro))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                },
            };
            columnWidths = new float[] { 100f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);

            foreach (var category in DataSource)
            {
                //exámenes
                cells = new List <PdfPCell>()
                {
                    new PdfPCell(new Phrase("* ", fontTitleTable))
                    {
                        HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                    },
                    new PdfPCell(new Phrase(category.v_CategoryName, fontTitleTable))
                    {
                        HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                    },
                };
                columnWidths = new float[] { 10f, 90f };
                table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
                document.Add(table);

                foreach (var component in category.Componentes)
                {
                    string estado = "";
                    var    obj    = ListAdditional.Find(x => x.ComponentId == component.v_ComponentId);
                    if (obj != null)
                    {
                        if (obj.IsProcessed == 1)
                        {
                            estado = " ( AGENDADO)";
                        }
                        else
                        {
                            estado = " ( POR AGENDAR )";
                        }
                    }

                    cells = new List <PdfPCell>()
                    {
                        new PdfPCell(new Phrase("- ", fontColumnValue))
                        {
                            HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                        },
                        new PdfPCell(new Phrase(component.v_ComponentName + estado, fontColumnValue))
                        {
                            HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.WHITE
                        },
                    };
                    columnWidths = new float[] { 15f, 85f };
                    table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
                    document.Add(table);
                }
            }



            //datos medicos
            var    cellFirma = new PdfPCell();
            string NombreMedico = "---", CMP = "---";
            if (usuarioGraba != null)
            {
                NombreMedico = usuarioGraba.Nombre == null ? "---" : usuarioGraba.Nombre;
                CMP          = usuarioGraba == null ? "---" : usuarioGraba.CMP;

                if (usuarioGraba.Firma != null)
                {
                    cellFirma = new PdfPCell(HandlingItextSharp.GetImage(usuarioGraba.Firma, null, null, 110, 40))
                    {
                        Colspan = 1, Rowspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, UseVariableBorders = true, BorderColor = BaseColor.BLACK
                    };
                }
            }
            else
            {
                cellFirma = new PdfPCell(new Phrase("FIRMA", fontTitle2_))
                {
                    Colspan = 1, Rowspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.BLACK
                };
            }


            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("DATOS MÉDICOS", fontTitle2))
                {
                    Colspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.BLACK
                },
                cellFirma,
                new PdfPCell(new Phrase("NOMBRE:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.BLACK
                },
                new PdfPCell(new Phrase(NombreMedico, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.BLACK
                },

                new PdfPCell(new Phrase("CMP:", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.BLACK
                },
                new PdfPCell(new Phrase(CMP, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20f, BorderColor = BaseColor.BLACK
                },
            };
            columnWidths = new float[] { 15f, 35f, 50f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion


            document.Close();
            writer.Close();
            writer.Dispose();
        }
 private bool CompareColors(BaseColor c1, BaseColor c2) {
     if (c1 == null && c2 == null)
         return true;
     if (c1 == null || c2 == null)
         return false;
     if (c1 is ExtendedColor)
         return c1.Equals(c2);
     return c2.Equals(c1);
 }
            public void LinePrint(Document doc, float height, float width, BaseColor color, int allign, int rotate)
            {
                Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(height, width, color, allign, rotate)));

                doc.Add(p);
            }
Beispiel #55
0
 /** 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) {
     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;
 }
Beispiel #56
0
        private void Text(string text, string nameFont, int sizeFont, float positionX, float positionY, BaseColor color, int align)
        {
            CheckPosition(30);
            var font = GetFont(nameFont);

            this._contentByte.SetColorFill(color);
            this._contentByte.SetFontAndSize(font, sizeFont);
            this._contentByte.BeginText();
            this._contentByte.ShowTextAligned(align, text, positionX, positionY, 0);
            this._contentByte.EndText();
        }
     /**
      * Converts a <CODE>BaseColor</CODE> into a HTML representation of this <CODE>BaseColor</CODE>.
      *
      * @param   color   the <CODE>BaseColor</CODE> that has to be converted.
      * @return  the HTML representation of this <COLOR>BaseColor</COLOR>
      */
 
     public static String Encode(BaseColor color) {
         StringBuilder buffer = new StringBuilder("#");
         if (color.R < 16) {
             buffer.Append('0');
         }
         buffer.Append(System.Convert.ToString(color.R, 16));
         if (color.G < 16) {
             buffer.Append('0');
         }
         buffer.Append(System.Convert.ToString(color.G, 16));
         if (color.B < 16) {
             buffer.Append('0');
         }
         buffer.Append(System.Convert.ToString(color.B, 16));
         return buffer.ToString();
     }
Beispiel #58
0
 internal void TextCenter(string text, string nameFont, int sizeFont, BaseColor colorFont, float positionX, float positionY)
 => Text(text, nameFont, sizeFont, positionX, positionY, colorFont, Element.ALIGN_CENTER);
Beispiel #59
0
 internal ColorDetails AddSimplePatternColorspace(BaseColor color) {
     int type = ExtendedColor.GetType(color);
     if (type == ExtendedColor.TYPE_PATTERN || type == ExtendedColor.TYPE_SHADING)
         throw new Exception(MessageLocalization.GetComposedMessage("an.uncolored.tile.pattern.can.not.have.another.pattern.or.shading.as.color"));
     switch (type) {
         case ExtendedColor.TYPE_RGB:
             if (patternColorspaceRGB == null) {
                 patternColorspaceRGB = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(PdfName.DEVICERGB);
                 AddToBody(array, patternColorspaceRGB.IndirectReference);
             }
             return patternColorspaceRGB;
         case ExtendedColor.TYPE_CMYK:
             if (patternColorspaceCMYK == null) {
                 patternColorspaceCMYK = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(PdfName.DEVICECMYK);
                 AddToBody(array, patternColorspaceCMYK.IndirectReference);
             }
             return patternColorspaceCMYK;
         case ExtendedColor.TYPE_GRAY:
             if (patternColorspaceGRAY == null) {
                 patternColorspaceGRAY = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(PdfName.DEVICEGRAY);
                 AddToBody(array, patternColorspaceGRAY.IndirectReference);
             }
             return patternColorspaceGRAY;
         case ExtendedColor.TYPE_SEPARATION: {
             ColorDetails details = AddSimple(((SpotColor)color).PdfSpotColor);
             ColorDetails patternDetails;
             documentSpotPatterns.TryGetValue(details, out patternDetails);
             if (patternDetails == null) {
                 patternDetails = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(details.IndirectReference);
                 AddToBody(array, patternDetails.IndirectReference);
                 documentSpotPatterns[details] = patternDetails;
             }
             return patternDetails;
         }
         default:
             throw new Exception(MessageLocalization.GetComposedMessage("invalid.color.type"));
     }
 }
Beispiel #60
0
 /// <summary>
 /// Constructs a RtfShapeProperty with a Color value.
 /// </summary>
 /// <param name="name">The property name to use.</param>
 /// <param name="value">The Color value to use.</param>
 public RtfShapeProperty(string name, BaseColor value)
 {
     _name  = name;
     _value = value;
     _type  = PropertyTypeColor;
 }