SetBackground() публичный Метод

Sets the color of the background Chunk.
public SetBackground ( BaseColor color ) : Chunk
color BaseColor the color of the background
Результат Chunk
Пример #1
5
        public void CreateTaggedPdf15() {
            InitializeDocument("15");

            Paragraph p = new Paragraph();
            Chunk chunk = new Chunk("Hello tagged world!");
            chunk.SetBackground(new BaseColor(255, 0, 255));
            chunk.Font = FontFactory.GetFont("TimesNewRoman", 20, BaseColor.ORANGE);
            chunk.SetUnderline(BaseColor.PINK, 1.2f, 1, 1, 1, 0);
            p.Add(chunk);

            document.Add(p);
            document.Close();
            int[] nums = new int[] {3};
            CheckNums(nums);
            CompareResults("15");
        }
Пример #2
0
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream).InitialLeading = 16;
        // step 3
        document.Open();
        // add the ID in another font
        Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
        // step 4
        using (var c =  AdoDB.Provider.CreateConnection()) {
          c.ConnectionString = AdoDB.CS;
          using (DbCommand cmd = c.CreateCommand()) {
            cmd.CommandText = 
              "SELECT country,id FROM film_country ORDER BY country";
            c.Open();
            using (var r = cmd.ExecuteReader()) {
              while (r.Read()) {
                var country = r.GetString(0);
                var ID = r.GetString(1);
                document.Add(new Chunk(country));
                document.Add(new Chunk(" "));
                Chunk id = new Chunk(ID, font);
                // with a background color
                id.SetBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
                // and a text rise
                id.SetTextRise(6);
                document.Add(id);
                document.Add(Chunk.NEWLINE);
              }
            }
          }
        }
      }
    }
Пример #3
0
        public void CreateTaggedPdf16() {
            InitializeDocument("16");

            Paragraph p = new Paragraph();
            Chunk chunk = new Chunk("Hello tagged world!");
            chunk.SetBackground(new BaseColor(255, 0, 255));
            chunk.Font = FontFactory.GetFont("TimesNewRoman", 20, BaseColor.ORANGE);
            chunk.SetUnderline(BaseColor.PINK, 1.2f, 1, 1, 1, 0);
            p.Add(chunk);
            PdfDiv div = new PdfDiv();
            div.AddElement(p);
            document.Add(div);

            document.Add(new Paragraph("This paragraph appears between 2 div blocks"));

            div = new PdfDiv();
            div.AddElement(new Paragraph(text));
            document.Add(div);


            document.Close();
            int[] nums = new int[] {48, 7};
            CheckNums(nums);
            CompareResults("16");
        }
Пример #4
0
        public static Chunk GetChunk(Properties attributes)
        {
            Chunk chunk = new Chunk();

            chunk.Font = FontFactory.GetFont(attributes);
            String value;

            value = attributes[ElementTags.ITEXT];
            if (value != null) {
                chunk.Append(value);
            }
            value = attributes[ElementTags.LOCALGOTO];
            if (value != null) {
                chunk.SetLocalGoto(value);
            }
            value = attributes[ElementTags.REMOTEGOTO];
            if (value != null) {
                String page = attributes[ElementTags.PAGE];
                if (page != null) {
                    chunk.SetRemoteGoto(value, int.Parse(page));
                }
                else {
                    String destination = attributes[ElementTags.DESTINATION];
                    if (destination != null) {
                        chunk.SetRemoteGoto(value, destination);
                    }
                }
            }
            value = attributes[ElementTags.LOCALDESTINATION];
            if (value != null) {
                chunk.SetLocalDestination(value);
            }
            value = attributes[ElementTags.SUBSUPSCRIPT];
            if (value != null) {
                chunk.SetTextRise(float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo));
            }
            value = attributes[Markup.CSS_KEY_VERTICALALIGN];
            if (value != null && value.EndsWith("%")) {
                float p = float.Parse(value.Substring(0, value.Length - 1), System.Globalization.NumberFormatInfo.InvariantInfo) / 100f;
                chunk.SetTextRise(p * chunk.Font.Size);
            }
            value = attributes[ElementTags.GENERICTAG];
            if (value != null) {
                chunk.SetGenericTag(value);
            }
            value = attributes[ElementTags.BACKGROUNDCOLOR];
            if (value != null) {
                chunk.SetBackground(Markup.DecodeColor(value));
            }
            return chunk;
        }
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            float[] ringColumns = new float[] { 300, 300, 300, 300 };

            User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDetails(userShow.ShowID);

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(userShow.ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            string currentJudge = "";
            int currentRingID = 0;
            int ShowDetailsID = -1;
            int PrevShowDetailsID = -1;
            PdfPTable rings = new PdfPTable(ringColumns);

            int ringCnt = 0;
            PdfPCell cell = null;
            PdfPTable ringDetails = null;
            PdfPTable classDetailsTable = null;
            List<int> dogsRunningToday = new List<int>();
            PdfPTable headerPage = null;
            List<TeamPairsTrioDto> pairsTeams = new List<TeamPairsTrioDto>();
            try
            {
                foreach (DataRow ringRow in ringList.Tables[0].Rows)
                {
                    Rings ring = new Rings(ringRow);
                    int RingID = Convert.ToInt32(ringRow["RingID"]);
                    int EntryType = Convert.ToInt32(ringRow["EntryType"]);
                    int Lho = Convert.ToInt32(ringRow["Lho"]);
                    ShowDetailsID = Convert.ToInt32(ringRow["ShowDetailsID"]);

                    if (ringRow.IsNull("ClassID"))
                    {
                        continue;
                    }
                    int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                    int ClassNo = Convert.ToInt32(ringRow["ClsNo"]);
                    DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                    if (rowDT != dt)
                    {
                        if (currentRingID != 0)
                        {
                            if (ringCnt % MaxColumns != 0)
                            {
                                var remind = ringCnt % MaxColumns;
                                while (remind-- > 0)
                                {
                                    cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                    cell.BorderWidth = 0;
                                    rings.AddCell(cell);
                                }
                            }
                            if (dogsRunningToday.Count() > 0 || UserID == -1)
                            {
                                doc.Add(headerPage);
                                doc.Add(rings);
                                if (UserID > -1)
                                {
                                    if (currentUser.UserID != UserID)
                                    {
                                        User defaultHandler = new User(UserID);
                                    }
                                }

                                doc.NewPage();
                                pageCount++;
                            }
                        }

                        dogsRunningToday.Clear();
                        if (UserID > -1)
                        {
                            if (currentUser.UserID == UserID)
                            {
                                headerPage = DrawHeader(show, rowDT, currentUser, userShow);
                            }
                            else
                            {
                                User defaultHandler = new User(UserID);
                                headerPage = DrawHeader(show, rowDT, defaultHandler, userShow);
                            }
                        }
                        else
                        {
                            headerPage = DrawHeader(show, rowDT, null, null);

                        }
                        dt = rowDT;
                        rings = new PdfPTable(ringColumns);
                        rings.WidthPercentage = 100;
                        ringCnt = 0;
                    }

                    if (currentRingID != RingID)
                    {
                        currentJudge = "";
                        ringCnt++;
                        ringDetails = new PdfPTable(1);
                        rings.AddCell(new PdfPCell(ringDetails));

                        //List<Judge> judgeList = Judge.getJudgesForRingList(RingID);
                        string JudgeName = Judge.getJudgeForClass(ClassID).Name;
                        int ClsCount = DogClasses.GetDogsInRing(RingID);

                        cell = new PdfPCell(new Phrase(new Chunk(string.Format("Ring No {0} ({1})", ringRow["RingNo"].ToString(), ClsCount), judgeFont)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        ringDetails.AddCell(cell);

                        if (currentJudge != JudgeName)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(JudgeName), judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);
                            currentJudge = JudgeName;
                        }
                        currentRingID = RingID;
                        classDetailsTable = new PdfPTable(DetailsColWidths);
                        classDetailsTable.DefaultCell.BorderWidth = 0;
                        ringDetails.AddCell(classDetailsTable);
                    }
                    else
                    {
                        string JudgeName = Judge.getJudgeForClass(ClassID).Name;
                        if (currentJudge != JudgeName)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("  ", judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);
                            cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(JudgeName), judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);

                            classDetailsTable = new PdfPTable(DetailsColWidths);
                            classDetailsTable.DefaultCell.BorderWidth = 0;
                            ringDetails.AddCell(classDetailsTable);
                            currentJudge = JudgeName;
                        }
                    }
                    DataSet dogsList = d.GetDogsInClass(userShow.Userid, ClassID);
                    int dogsInClass = d.dogsInClassCount(ClassID);
                    List<DogClassCount> dcCounts = DogClasses.GetEntryCountsByClassId(userShow.ShowID, ClassID);

                    String clsName;
                    var part = Convert.ToInt32(ringRow["Part"]);
                    var lhoInd = "";
                    var dogsInClassDisplay = "";
                    if (dcCounts.Count > 1)
                    {
                        if (Lho == 1) {
                            dogsInClassDisplay = String.Format("({0}/{1})", dcCounts[0].Count, dcCounts[1].Count);
                        }
                        else
                        {
                            dogsInClassDisplay = String.Format("({0}/{1})", dcCounts[1].Count, dcCounts[0].Count);
                        }
                    }
                    else
                    {
                        dogsInClassDisplay = String.Format("({0})", dogsInClass);
                    }

                    if (Lho == 1)
                    {
                        lhoInd = "(FH 1st)";
                    }
                    else if (Lho == 2)
                    {
                        lhoInd = "(LHO 1st)";
                    }
                    if (EntryType != 10)
                    {
                        clsName = new ShowClasses(ClassID).NormalName(withClassNo:false, useAbbrFlag:true);
                    }
                    else
                    {
                        clsName = String.Format("{0} {1} {2} ",
                                        ShowClasses.expandHeight(ringRow),
                                        ringRow["LongName"].ToString().Trim(),
                                        ringRow["name"].ToString().Trim());
                    }
                    clsName = clsName.Replace("(Special Class", "S");
                    clsName = clsName.Replace("(Money Class", "Money");
                    clsName = clsName.Replace("First Place Processing", "FPP");
                    clsName = clsName.Replace("First Contact", "FC");
                    clsName = clsName.Replace("Qualifier", "Q");

                    if (part > 0 && EntryType != 10)
                    {
                        clsName += "Pt " + part;
                    }

                    if (dogsList.Tables[0].Rows.Count > 0)
                    {
                        /*
                        Combined 1-7 All Allsorts Agility sponsored by paws for a walk
                        Combined 6-7 Medium Agility

                            * */
                        var WrapClassDescription = clsName.Length > 45;
                        Phrase[] tmpCells = new Phrase[3];
                        tmpCells[0] = new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogInClass));
                        tmpCells[1] = new Phrase(new Chunk(clsName, dogInClass));
                        tmpCells[2] = new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass ));

                        int countDogs = 0;
                        int DefaultHandler;

                        Paragraph p = new Paragraph();
                        List<Paragraph> allDogsInClass = new List<Paragraph>();
                        foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                        {
                            var dogLho = Convert.ToInt32(dogRow["Lho"]);
                            int DogID = Convert.ToInt32(dogRow["DogID"]);
                            DefaultHandler = Convert.ToInt32(dogRow["DefaultHandler"]);
                            if (DefaultHandler == 0) DefaultHandler = -1;
                            if ((DefaultHandler == -1 && currentUser.UserID == UserID) ||
                                (DefaultHandler == UserID)
                                )
                            {
                                if (countDogs == 0)
                                {
                                    cell = new PdfPCell(tmpCells[0]);
                                    cell.BorderWidth = 0;
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                    classDetailsTable.AddCell(cell);
                                    var namePara = new Paragraph();
                                    namePara.Add(tmpCells[1]);
                                    namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                                    p.Add(namePara);
                                }
                                if (!dogsRunningToday.Contains(DogID))
                                {
                                    dogsRunningToday.Add(DogID);
                                }
                                String dogName = dogRow["DogName"].ToString();
                                if (dogName.Length == 0)
                                {
                                    dogName = dogRow["KCName"].ToString();
                                }
                                var chunk = new Chunk("   ", dogDetailsInClass);
                                chunk.SetBackground(new Color(System.Drawing.ColorTranslator.FromHtml(dogRow["DogColour"].ToString())));

                                var dogPara = new Paragraph();
                                dogPara.Add(new Phrase(chunk));

                                if (TeamPairsManager.isMultiDog( EntryType ))
                                {
                                    pairsTeams.Add(new TeamPairsTrioDto
                                    {
                                        ClassId = ClassID,
                                        ClassNo = ClassNo,
                                        DogId = DogID,
                                        DogName = dogName,
                                        RO = -1
                                    });
                                }
                                dogPara.Add(new Phrase(new Chunk(String.Format(" [{1}] {0}", Fpp.Core.Utils.TitleCaseString(dogName), dogRow["RO"]), dogDetailsInClass)));
                                dogPara.Add(new Phrase(new Chunk(String.Format("{0}", (dogLho == 0 ? "" : " (LHO)")), font8)));
                                dogPara.Add(Chunk.NEWLINE);

                                int AltHandler = Convert.ToInt32(dogRow["AltHandler"]);
                                String HandlerName = "";
                                if (AltHandler > 0)
                                {
                                    User u = new User(AltHandler);
                                    HandlerName = u.Name;
                                    dogPara.Add(new Phrase(new Chunk(String.Format("Handler:{0}", Fpp.Core.Utils.TitleCaseString(HandlerName)), dogInClass)));
                                }
                                allDogsInClass.Add(dogPara);
                                countDogs++;
                            }
                            else
                            {
                                if (defaultUsers != null && defaultUsers.IndexOf(DefaultHandler) == -1)
                                {
                                    defaultUsers.Add(DefaultHandler);
                                }
                            }
                        }
                        if (countDogs == 0)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);

                            var namePara = new Paragraph();
                            namePara.Add(new Phrase(new Chunk(clsName, dogNotInClass)));
                            namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                            p.Add(namePara);
                            cell = new PdfPCell(p);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;
                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);
                        }
                        else
                        {

                            cell = new PdfPCell(p);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;

                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(tmpCells[2]);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk("", dogDetailsInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;
                            classDetailsTable.AddCell(cell);

                            var tbl4Dogs = new PdfPTable(1);
                            foreach (var item in allDogsInClass)
                            {
                                cell = new PdfPCell(new Phrase(item));
                                cell.BorderWidth = 0;
                                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                                tbl4Dogs.AddCell(cell);
                            }
                            cell = new PdfPCell();
                            cell.BorderWidth = 0;
                            cell.FixedHeight = 4f;
                            tbl4Dogs.AddCell(cell);

                            cell = new PdfPCell(tbl4Dogs);
                            cell.BorderWidth = 0;
                            cell.Colspan = 2;
                            classDetailsTable.AddCell(cell);
                        }
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                        var namePara = new Paragraph();
                        namePara.Add(new Phrase(new Chunk(clsName, dogNotInClass)));
                        namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                        cell = new PdfPCell(namePara);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = false;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                    }

                    PrevShowDetailsID = ShowDetailsID;
                }

                if (dogsRunningToday.Count() > 0 || UserID == -1)
                {
                    if (ringCnt % MaxColumns != 0)
                    {
                        var remind = ringCnt % MaxColumns;
                        while (remind-- > 0)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                            cell.BorderWidth = 0;
                            rings.AddCell(cell);
                        }
                        doc.Add(headerPage);
                        doc.Add(rings);
                    }

                    if (UserID > -1)
                    {
                        if (currentUser.UserID != UserID)
                        {
                            User defaultHandler = new User(UserID);
                        }
                    }
                    doc.NewPage();
                    pageCount++;
                }
                else
                {
                    if (dogsRunningToday.Count() > 0)
                    {
                        if (ringCnt % MaxColumns != 0)
                        {
                            var remind = ringCnt % MaxColumns;
                            while (remind-- > 0)
                            {
                                cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                cell.BorderWidth = 0;
                                rings.AddCell(cell);
                            }
                            doc.Add(headerPage);
                            doc.Add(rings);
                        }

                        if (UserID > -1)
                        {
                            if (currentUser.UserID != UserID)
                            {
                                User defaultHandler = new User(UserID);
                            }
                        }
                        doc.NewPage();
                        pageCount++;
                    }
                }
            }
            catch (Exception e)
            {
                AppException.LogError($"Error Running Plan:{e.Message},{e.StackTrace}");
            }
        }
Пример #6
0
        /**
         *
         * @param c the Chunk to apply CSS to.
         * @param t the tag containing the chunk data
         * @return the styled chunk
         */

        virtual public Chunk Apply(Chunk c, Tag t)
        {
            Font f = ApplyFontStyles(t);
            float size = f.Size;
            String value = null;
            IDictionary<String, String> rules = t.CSS;
            foreach (KeyValuePair<String, String> entry in rules)
            {
                String key = entry.Key;
                value = entry.Value;
                if (Util.EqualsIgnoreCase(CSS.Property.FONT_STYLE, key)) {
                    if (Util.EqualsIgnoreCase(CSS.Value.OBLIQUE, value)) {
                        c.SetSkew(0, 12);
                    }
                } else if (Util.EqualsIgnoreCase(CSS.Property.LETTER_SPACING, key)) {
                    String letterSpacing = entry.Value;
                    float letterSpacingValue = 0f;
                    if (utils.IsRelativeValue(value)) {
                        letterSpacingValue = utils.ParseRelativeValue(letterSpacing, f.Size);
                    } else if (utils.IsMetricValue(value)) {
                        letterSpacingValue = utils.ParsePxInCmMmPcToPt(letterSpacing);
                    }
                    c.SetCharacterSpacing(letterSpacingValue);
                } else if (Util.EqualsIgnoreCase(CSS.Property.XFA_FONT_HORIZONTAL_SCALE, key)) {
                    // only % allowed; need a catch block NumberFormatExc?
                    c.SetHorizontalScaling(
                        float.Parse(value.Replace("%", ""))/100);
                }
            }
            // following styles are separate from the for each loop, because they are based on font settings like size.
            if (rules.TryGetValue(CSS.Property.VERTICAL_ALIGN, out value))
            {
                if (Util.EqualsIgnoreCase(CSS.Value.SUPER, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TOP, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_TOP, value)) {
                    c.SetTextRise((float) (size/2 + 0.5));
                } else if (Util.EqualsIgnoreCase(CSS.Value.SUB, value)
                    || Util.EqualsIgnoreCase(CSS.Value.BOTTOM, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_BOTTOM, value)) {
                    c.SetTextRise(-size/2);
                } else {
                    c.SetTextRise(utils.ParsePxInCmMmPcToPt(value));
                }
            }
            String xfaVertScale;
            if (rules.TryGetValue(CSS.Property.XFA_FONT_VERTICAL_SCALE, out xfaVertScale))
            {
                if (xfaVertScale.Contains("%"))
                {
                    size *= float.Parse(xfaVertScale.Replace("%", ""))/100;
                    c.SetHorizontalScaling(100/float.Parse(xfaVertScale.Replace("%", "")));
                }
            }
            if (rules.TryGetValue(CSS.Property.TEXT_DECORATION, out value)) {
                String[] splitValues = new Regex(@"\s+").Split(value);
                foreach (String curValue in splitValues) {
                    if (Util.EqualsIgnoreCase(CSS.Value.UNDERLINE, curValue)) {
                        c.SetUnderline(0.75f, -size/8f);
                    }
                    if (Util.EqualsIgnoreCase(CSS.Value.LINE_THROUGH, curValue)) {
                        c.SetUnderline(0.75f, size/4f);
                    }
                }
            }
            if (rules.TryGetValue(CSS.Property.BACKGROUND_COLOR, out value))
            {
                c.SetBackground(HtmlUtilities.DecodeColor(value));
            }
            f.Size = size;
            c.Font = f;


            float? leading = null;
            value = null;
            if (rules.TryGetValue(CSS.Property.LINE_HEIGHT, out value)) {
                if (utils.IsNumericValue(value)) {
                    leading = float.Parse(value) * c.Font.Size;
                } else if (utils.IsRelativeValue(value)) {
                    leading = utils.ParseRelativeValue(value, c.Font.Size);
                } else if (utils.IsMetricValue(value)) {
                    leading = utils.ParsePxInCmMmPcToPt(value);
                }
            }

            if (leading != null) {
                c.setLineHeight((float)leading);
            }
            return c;
        }
Пример #7
0
        /**
         *
         * @param c the Chunk to apply CSS to.
         * @param t the tag containing the chunk data
         * @return the styled chunk
         */

        public Chunk Apply(Chunk c, Tag t)
        {
            Font f = ApplyFontStyles(t);
            float size = f.Size;
            String value = null;
            IDictionary<String, String> rules = t.CSS;
            foreach (KeyValuePair<String, String> entry in rules)
            {
                String key = entry.Key;
                value = entry.Value;
                if (Util.EqualsIgnoreCase(CSS.Property.FONT_STYLE, key)) {
                    if (Util.EqualsIgnoreCase(CSS.Value.OBLIQUE, value))
                    {
                        c.SetSkew(0, 12);
                    }
                } else if (Util.EqualsIgnoreCase(CSS.Property.LETTER_SPACING, key)) {
                    c.SetCharacterSpacing(utils.ParsePxInCmMmPcToPt(value));
                } else if (Util.EqualsIgnoreCase(CSS.Property.XFA_FONT_HORIZONTAL_SCALE, key)) {
                    // only % allowed; need a catch block NumberFormatExc?
                    c.SetHorizontalScaling(
                        float.Parse(value.Replace("%", ""))/100);
                }
            }
            // following styles are separate from the for each loop, because they are based on font settings like size.
            if (rules.TryGetValue(CSS.Property.VERTICAL_ALIGN, out value))
            {
                if (Util.EqualsIgnoreCase(CSS.Value.SUPER, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TOP, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_TOP, value)) {
                    c.SetTextRise((float) (size/2 + 0.5));
                } else if (Util.EqualsIgnoreCase(CSS.Value.SUB, value)
                    || Util.EqualsIgnoreCase(CSS.Value.BOTTOM, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_BOTTOM, value)) {
                    c.SetTextRise(-size/2);
                } else {
                    c.SetTextRise(utils.ParsePxInCmMmPcToPt(value));
                }
            }
            String xfaVertScale;
            if (rules.TryGetValue(CSS.Property.XFA_FONT_VERTICAL_SCALE, out xfaVertScale))
            {
                if (xfaVertScale.Contains("%"))
                {
                    size *= float.Parse(xfaVertScale.Replace("%", ""))/100;
                    c.SetHorizontalScaling(100/float.Parse(xfaVertScale.Replace("%", "")));
                }
            }
            if (rules.TryGetValue(CSS.Property.TEXT_DECORATION, out value))
            {
                // Restriction? In html a underline and a line-through is possible on one piece of text. A Chunk can set an underline only once.
                if (Util.EqualsIgnoreCase(CSS.Value.UNDERLINE, value))
                {
                    c.SetUnderline(0.75f, -size/8f);
                }
                if (Util.EqualsIgnoreCase(CSS.Value.LINE_THROUGH, value))
                {
                    c.SetUnderline(0.75f, size/4f);
                }
            }
            if (rules.TryGetValue(CSS.Property.BACKGROUND_COLOR, out value))
            {
                c.SetBackground(HtmlUtilities.DecodeColor(value));
            }
            f.Size = size;
            c.Font = f;
            return c;
        }
Пример #8
0
		/// <summary>
		/// Draws a block string
		/// </summary>
		/// <param name="txt"></param>
		/// <param name="x"></param>
		/// <param name="width"></param>
		/// <param name="fontAttrs"></param>
		/// <param name="textAttrs"></param>
		public void DrawBlockString(string txt, float x, float width,
		                            XmlAttributeCollection fontAttrs, XmlAttributeCollection textAttrs)
		{
			iTextSharp.text.Font font = CreateFontFromAttribute(fontAttrs);
			int align = PDFDrawItextSharpHelper.Align(
				Moon.PDFDraw.Helper.GetAttributeValue(AlignAttributeConstant, textAttrs, "Near"));
			
			iTextSharp.text.Chunk chunk = new iTextSharp.text.Chunk(txt, font);
			
			//20130605 :: mellorasinxelas
			BlockStyle backgroundDef = new BlockStyle( textAttrs );//load text background values.
			
			if(backgroundDef.BackgroundColor != null){
				chunk.SetBackground( new BaseColor(backgroundDef.BackgroundColor.Value) );//sets the same backcolor to the text.
			}
			//----
			float height = Moon.PDFDraw.Helper.GetFloatAttributeValue( "height", textAttrs, font.Size + (font.Size / 2));

			DrawBlockString(chunk, x, width, align, height, backgroundDef);
		}
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            String html = "";
            float[] ringColumns = new float[] { 300, 300, 300, 300};

            Font pageFont = FontFactory.GetFont("Arial", 22, Font.NORMAL);
            Font headerFont = new Font(Font.HELVETICA, 16, Font.BOLD, Color.BLACK);
            Font judgeFont = FontFactory.GetFont("Arial", 9, Font.BOLD);
            Font notInClassFont = new Font(Font.HELVETICA, 6, Font.NORMAL, Color.BLACK);
            Font inClassFont = new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK);
            Font font = new Font(Font.HELVETICA, 10, Font.NORMAL, Color.BLACK);
            Font font1 = FontFactory.GetFont("Arial", 18, Font.BOLD);
            Font dogNotInClass = new Font(Font.HELVETICA, 6, Font.NORMAL, Color.BLACK);
            Font dogInClass = new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK);
            Font dogDetailsInClass = new Font(Font.HELVETICA, 9, Font.BOLD, Color.BLACK);
            Fpp.WebModules.Business.User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDaysList(userShow.ShowID);
            doc.Add(new Paragraph(show.ShowName, pageFont));

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(userShow.ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            int currentRingID = 0;
            int ShowDetailsID = -1;
            int PrevShowDetailsID = -1;
            PdfPTable rings = new PdfPTable(ringColumns);

            int ringCnt = 0;
            PdfPCell cell = null;
            PdfPTable ringDetails = null;
            PdfPTable classDetailsTable = null;
            List<int> dogsRunningToday = new List<int>();
            foreach (DataRow ringRow in ringList.Tables[0].Rows)
            {
                int RingID = Convert.ToInt32(ringRow["RingID"]);
                ShowDetailsID = Convert.ToInt32(ringRow["ShowDetailsID"]);

                if (ringRow.IsNull("ClassID"))
                {
                    continue;
                }
                int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                if (rowDT != dt)
                {
                    if (currentRingID != 0)
                    {
                        if (ringCnt % 4 != 0)
                        {
                            var remind = ringCnt % 4;
                            while (remind-- > 0)
                            {
                                cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                cell.BorderWidth = 0;
                                rings.AddCell(cell);
                            }
                        }

                        doc.Add(rings);
                        if (currentUser.UserID == UserID)
                        {
                            doc.Add(getHandlerDetails(userShow, currentUser, PrevShowDetailsID, dogsRunningToday));
                        }
                        else
                        {
                            User defaultHandler = new User(UserID);
                            doc.Add(getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID, dogsRunningToday));
                        }
                        doc.NewPage();
                        if (dogsRunningToday.Count > 0)
                        {
                            pageCount++;
                        }
                    }
                    dogsRunningToday.Clear();
                    doc.Add(new Paragraph(rowDT.ToString("dddd d MMM"), headerFont));
                    doc.Add(new Paragraph("  ", judgeFont));
                    dt = rowDT;
                    rings = new PdfPTable(ringColumns);
                    rings.WidthPercentage = 100;
                    ringCnt = 0;
                }

                if (currentRingID != RingID)
                {
                    ringCnt++;
                    ringDetails = new PdfPTable(1);
                    rings.AddCell(new PdfPCell( ringDetails));

                    List<Judge> judgeList = Judge.getJudgesForRingList(RingID);

                    cell = new PdfPCell(new Phrase(new Chunk("Ring No " + ringRow["RingNo"].ToString(), judgeFont)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    ringDetails.AddCell(cell);

                    foreach (Judge judge in judgeList)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(judge.Name, judgeFont)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        ringDetails.AddCell(cell);
                    }
                    currentRingID = RingID;
                    classDetailsTable = new PdfPTable(new float[] { 50, 225, 100 });
                    classDetailsTable.DefaultCell.BorderWidth = 0;
                    ringDetails.AddCell(classDetailsTable);
                }
                html += "<tr>";
                DataSet dogsList = d.GetDogsInClass(userShow.Userid, ClassID);
                int DogsInClass = d.dogsInClassCount(ClassID);

                String clsName = String.Format("{0} {1} {2} {3}",
                                ShowClasses.expandCatagory(ringRow),
                                ShowClasses.expandHeight(ringRow),
                                ringRow["LongName"],
                                ringRow["name"]);
                String grades = ShowClasses.shortenGrades(ringRow);
                int ix = clsName.IndexOf("Grd");
                if (ix == -1) ix = clsName.IndexOf("Cmb");
                if (ix > -1)
                {
                    clsName = clsName.Substring(0, ix + 3) + " " + grades + " " + clsName.Substring(ix + 4);
                }
                else
                {
                    ix = clsName.IndexOf(" ");
                    clsName = clsName.Substring(0, ix) + " " + grades + " " + clsName.Substring(ix + 1);
                }

                if (dogsList.Tables[0].Rows.Count > 0)
                {
                    Phrase[] tmpCells = new Phrase[3];
                    tmpCells[0] = new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogInClass));
                    tmpCells[1] = new Phrase(new Chunk(clsName, dogInClass));
                    tmpCells[2] = new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogInClass));

                    int countDogs = 0;
                    int DefaultHandler;
                    Paragraph p = new Paragraph();
                    foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                    {
                        int DogID = Convert.ToInt32(dogRow["DogID"]);
                        DefaultHandler = Convert.ToInt32(dogRow["DefaultHandler"]);
                        if (DefaultHandler == 0) DefaultHandler = -1;
                        if ((DefaultHandler == -1 && currentUser.UserID == UserID) ||
                            (DefaultHandler == UserID)
                            )
                        {
                            if (countDogs == 0)
                            {
                                cell = new PdfPCell(tmpCells[0]);
                                cell.BorderWidth = 0;
                                cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                classDetailsTable.AddCell(cell);
                                p.Add(tmpCells[1]);
                                p.Add(Chunk.NEWLINE);
                            }
                            if (!dogsRunningToday.Contains(DogID))
                            {
                                dogsRunningToday.Add(DogID);
                            }
                            String img = "<img src='data:image/gif;base64," + CreateImage(dogRow["DogColour"].ToString()) + "' />";
                            String dogName = dogRow["DogName"].ToString();
                            if (dogName.Length == 0)
                            {
                                dogName = dogRow["KCName"].ToString();
                            }
                            var chunk = new Chunk("   ", dogDetailsInClass);
                            chunk.SetBackground(new Color( System.Drawing.ColorTranslator.FromHtml(dogRow["DogColour"].ToString())  ));
                            p.Add(new Phrase(chunk));
                            p.Add(new Phrase(new Chunk(String.Format(" [{1}] {0}", dogName, dogRow["RO"]), dogDetailsInClass)));
                            p.Add(Chunk.NEWLINE);

                            int AltHandler = Convert.ToInt32(dogRow["AltHandler"]);
                            String HandlerName = "";
                            if (AltHandler > 0)
                            {
                                User u = new User(AltHandler);
                                HandlerName = u.Name;

                                html += "<div class='altHandler'>Handler:" + AltHandler + "</div>";
                                p.Add(Chunk.NEWLINE);
                                p.Add(new Phrase(new Chunk(String.Format("Handler:", AltHandler),dogInClass)));
                            }
                            countDogs++;
                        }
                        else
                        {
                            if (defaultUsers != null && defaultUsers.IndexOf(DefaultHandler) == -1)
                            {
                                defaultUsers.Add(DefaultHandler);
                            }
                        }
                    }
                    if (countDogs == 0)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(clsName, dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = true;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);
                    }
                    else
                    {

                        cell = new PdfPCell(p);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = true;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(tmpCells[2]);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);
                    }
                }
                else
                {
                    cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    classDetailsTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(clsName, dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    classDetailsTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    classDetailsTable.AddCell(cell);
                }

                PrevShowDetailsID = ShowDetailsID;
            }

            if (ringCnt % 4 != 0)
            {
                var remind = ringCnt % 4;
                while (remind-- > 0)
                {
                    cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                    cell.BorderWidth = 0;
                    rings.AddCell(cell);

                }
            }

            if (currentUser.UserID == UserID)
            {
                doc.Add(getHandlerDetails(userShow, currentUser, PrevShowDetailsID, dogsRunningToday));
            }
            else
            {
                User defaultHandler = new User(UserID);
                doc.Add(getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID, dogsRunningToday));
            }
            doc.NewPage();
        }
Пример #10
0
  /*
  * (non-Javadoc)
  *
  * @see
  * com.itextpdf.tool.xml.css.CssApplier#apply(com.itextpdf.text.Element,
  * com.itextpdf.tool.xml.Tag)
  */
 public Chunk Apply(Chunk c, Tag t) {
     String fontName = null;
     String encoding = BaseFont.CP1252;
     float size = new FontSizeTranslator().GetFontSize(t);
     int style = Font.UNDEFINED;
     BaseColor color = null;
     IDictionary<String, String> rules = t.CSS;
     foreach (KeyValuePair<String, String> entry in rules) {
         String key = entry.Key;
         String value = entry.Value;
         if (Util.EqualsIgnoreCase(CSS.Property.FONT_WEIGHT, key)) {
             if (CSS.Value.BOLD.Contains(value)) {
                 if (style == Font.ITALIC) {
                     style = Font.BOLDITALIC;
                 }
                 else {
                     style = Font.BOLD;
                 }
             }
             else {
                 if (style == Font.BOLDITALIC) {
                     style = Font.ITALIC;
                 } else {
                     style = Font.NORMAL;
                 }
             }
         } else if (Util.EqualsIgnoreCase(CSS.Property.FONT_STYLE, key)) {
             if (Util.EqualsIgnoreCase(value, CSS.Value.ITALIC)) {
                 if (style == Font.BOLD)
                     style = Font.BOLDITALIC;
                 else
                     style = Font.ITALIC;
             }
             if (Util.EqualsIgnoreCase(value, CSS.Value.OBLIQUE)) {
                 c.SetSkew(0, 12);
             }
         } else if (Util.EqualsIgnoreCase(CSS.Property.FONT_FAMILY, key)) {
             if (value.Contains(",")){
                 String[] fonts = value.Split(',');
                 foreach (String s in fonts) {
                     string s2 = s.Trim();
                     if (!Util.EqualsIgnoreCase(FontFactory.GetFont(s2).Familyname, "unknown")){
                         fontName = s2;
                         break;
                     }
                 }
             } else {
                 fontName = value;
             }
         } else if (Util.EqualsIgnoreCase(CSS.Property.COLOR, key)) {
             color = HtmlUtilities.DecodeColor(value);
         } else if (Util.EqualsIgnoreCase(CSS.Property.LETTER_SPACING, key)) {
             c.SetCharacterSpacing(utils.ParsePxInCmMmPcToPt(value));
         } else if (rules.ContainsKey(CSS.Property.XFA_FONT_HORIZONTAL_SCALE)) { // only % allowed; need a catch block NumberFormatExc?
             c.SetHorizontalScaling(float.Parse(rules[CSS.Property.XFA_FONT_HORIZONTAL_SCALE].Replace("%", ""), CultureInfo.InvariantCulture)/100f);
         }
     }
     // following styles are separate from the for each loop, because they are based on font settings like size.
     if (rules.ContainsKey(CSS.Property.VERTICAL_ALIGN)) {
         String value = rules[CSS.Property.VERTICAL_ALIGN];
         if (Util.EqualsIgnoreCase(value, CSS.Value.SUPER)||Util.EqualsIgnoreCase(value, CSS.Value.TOP)||Util.EqualsIgnoreCase(value, CSS.Value.TEXT_TOP)) {
             c.SetTextRise((float) (size / 2 + 0.5));
         } else if (Util.EqualsIgnoreCase(value, CSS.Value.SUB)||Util.EqualsIgnoreCase(value, CSS.Value.BOTTOM)||Util.EqualsIgnoreCase(value, CSS.Value.TEXT_BOTTOM)) {
             c.SetTextRise(-size / 2);
         } else {
             c.SetTextRise(utils.ParsePxInCmMmPcToPt(value));
         }
     }
     String xfaVertScale;
     rules.TryGetValue(CSS.Property.XFA_FONT_VERTICAL_SCALE, out xfaVertScale);
     if (null != xfaVertScale) { // only % allowed; need a catch block NumberFormatExc?
         if (xfaVertScale.Contains("%")) {
             size *= float.Parse(xfaVertScale.Replace("%", ""), CultureInfo.InvariantCulture)/100;
             c.SetHorizontalScaling(100/float.Parse(xfaVertScale.Replace("%", ""), CultureInfo.InvariantCulture));
         }
     }
     if (rules.ContainsKey(CSS.Property.TEXT_DECORATION)) { // Restriction? In html a underline and a line-through is possible on one piece of text. A Chunk can set an underline only once.
         String value = rules[CSS.Property.TEXT_DECORATION];
         if (Util.EqualsIgnoreCase(CSS.Value.UNDERLINE, value)) {
             c.SetUnderline(0.75f, -size/8f);
         }
         if (Util.EqualsIgnoreCase(CSS.Value.LINE_THROUGH, value)) {
             c.SetUnderline(0.75f, size/4f);
         }
     }
     if (rules.ContainsKey(CSS.Property.BACKGROUND_COLOR)) {
         c.SetBackground(HtmlUtilities.DecodeColor(rules[CSS.Property.BACKGROUND_COLOR]));
     }
     Font f  = FontFactory.GetFont(fontName, encoding, BaseFont.EMBEDDED, size, style, color);
     c.Font = f;
     return c;
 }
Пример #11
0
        protected override Stream Read()
        {
            Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
            doc.AddTitle(Title);
            doc.AddCreationDate();
            doc.AddCreator("iTextSharp");
            doc.AddAuthor("文化中国");
            doc.AddSubject(w.Excerpt);
            doc.AddKeywords(w.Tags);
            using (MemoryStream stream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, stream);
                writer.SetEncryption(true, null, null, 0);
                writer.PageEvent = new HeaderFooterPdfPageEventHelper();

                doc.Open();

                Paragraph p = new Paragraph(Title, font);
                p.Alignment = 1;
                doc.Add(p);

                MatchCollection matches = regex.Matches(w.Script.Text);
                foreach (Match m in matches)
                {
                    Chunk chunk = new Chunk(m.Groups["cont"].Value);
                    switch (m.Groups["tag"].Value.ToLower())
                    {
                        case "h1":
                            font.Color = BaseColor.WHITE;
                            chunk.SetBackground(BaseColor.DARK_GRAY);
                            break;
                        case "p":
                            font.Color = BaseColor.BLACK;
                            break;
                    }
                    chunk.Font = font;
                    p = new Paragraph(chunk);
                    p.SetLeading(0.0f, 2.0f);
                    p.FirstLineIndent = 20f;
                    p.Alignment = 0;
                    doc.Add(p);
                }
                doc.Close();

                return new MemoryStream(stream.GetBuffer());
            }
        }
Пример #12
0
        protected override Stream Read()
        {
            Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
            doc.AddTitle(Title);
            doc.AddCreationDate();
            doc.AddCreator("iTextSharp");
            doc.AddAuthor("文化中国");
            doc.AddSubject(f.Brief);
            using (MemoryStream stream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, stream);
                writer.SetEncryption(true, null, null, PdfWriter.ALLOW_PRINTING);
                writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;
                writer.PageEvent = new HeaderFooterPdfPageEventHelper();

                doc.Open();

                foreach (var w in f.Webcasts.Where(w => w.Script != null).OrderBy(w => w.Aired))
                {
                    Paragraph p = new Paragraph(w.Title, font);
                    p.Alignment = 1;
                    Chapter chapter = new Chapter(p, 1);
                    chapter.NumberDepth = 0;
                    chapter.BookmarkTitle = w.Title;
                    chapter.TriggerNewPage = true;
                    doc.Add(chapter);

                    MatchCollection matches = regex.Matches(w.Script.Text);
                    foreach (Match m in matches)
                    {
                        Chunk chunk = new Chunk(m.Groups["cont"].Value);
                        switch (m.Groups["tag"].Value.ToLower())
                        {
                            case "h1":
                                font.Color = BaseColor.WHITE;
                                chunk.SetBackground(BaseColor.DARK_GRAY);
                                break;
                            case "p":
                                font.Color = BaseColor.BLACK;
                                break;
                        }
                        chunk.Font = font;
                        p = new Paragraph(chunk);
                        p.SetLeading(0.0f, 2.0f);
                        p.FirstLineIndent = 20f;
                        p.Alignment = 0;
                        doc.Add(p);
                    }
                }

                doc.Close();
                return new MemoryStream(stream.GetBuffer());
            }
        }
Пример #13
0
        public static void Genera(string sourcePath,string content)
        {
            sourcePath = HttpContext.Current.Server.MapPath(sourcePath);
            //定义一个Document,并设置页面大小为A4,竖向
            iTextSharp.text.Document doc = new Document(PageSize.A4);
            try
            {
                //写实例
                PdfWriter.GetInstance(doc, new FileStream(sourcePath, FileMode.Create));
                //打开document
                doc.Open();

                //载入字体
                BaseFont baseFont = BaseFont.CreateFont(
                    "C:\\WINDOWS\\FONTS\\SIMHEI.TTF", //黑体
                    BaseFont.IDENTITY_H, //横向字体
                    BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9);

                //写入一个段落, Paragraph
                doc.Add(new Paragraph("第一段:" + content, font));
                doc.Add(new Paragraph("这是第二段 !", font));

                #region 图片
                //以下代码用来添加图片,此时图片是做为背景加入到pdf文件当中的:

                Stream inputImageStream = new FileStream(HttpContext.Current.Server.MapPath("~/images/logo.jpg"), FileMode.Open, FileAccess.Read, FileShare.Read);
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                image.SetAbsolutePosition(0, 0);
                image.Alignment = iTextSharp.text.Image.UNDERLYING;    //这里可以设定图片是做为背景还是做为元素添加到文件中
                doc.Add(image);

                #endregion
                #region 其他元素
                doc.Add(new Paragraph("Hello World"));
                //另起一行。有几种办法建立一个段落,如:
                Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph.\n", FontFactory.GetFont(FontFactory.HELVETICA, 12)));
                Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12)));
                Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12));
                //所有有些对象将被添加到段落中:
                p1.Add("you can add string here\n\t");
                p1.Add(new Chunk("you can add chunks \n")); p1.Add(new Phrase("or you can add phrases.\n"));
                doc.Add(p1); doc.Add(p2); doc.Add(p3);

                //创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块:
                Chunk chunk = new Chunk("创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块", FontFactory.GetFont(FontFactory.COURIER, 20, iTextSharp.text.Font.COURIER, new iTextSharp.text.Color(255, 0, 0)));
                doc.Add(chunk);
                //如果你希望一些块有下划线或删除线,你可以通过改变字体风格简单做到:
                Chunk chunk1 = new Chunk("This text is underlined", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED));
                Chunk chunk2 = new Chunk("This font is of type ITALIC | STRIKETHRU", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.STRIKETHRU));
                //改变块的背景
                chunk2.SetBackground(new iTextSharp.text.Color(0xFF, 0xFF, 0x00));
                //上标/下标
                chunk1.SetTextRise(5);
                doc.Add(chunk1);
                doc.Add(chunk2);

                //外部链接示例:
                Anchor anchor = new Anchor("website", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED, new iTextSharp.text.Color(0, 0, 255)));
                anchor.Reference = "http://itextsharp.sourceforge.net";
                anchor.Name = "website";
                //内部链接示例:
                Anchor anchor1 = new Anchor("This is an internal link\n\n");
                anchor1.Name = "link1";
                Anchor anchor2 = new Anchor("Click here to jump to the internal link\n\f");
                anchor2.Reference = "#link1";
                doc.Add(anchor); doc.Add(anchor1); doc.Add(anchor2);

                //排序列表示例:
                List list = new List(true, 20);
                list.Add(new ListItem("First line"));
                list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?"));
                list.Add(new ListItem("Third line"));
                doc.Add(list);

                //文本注释:
                Annotation a = new Annotation("authors", "Maybe its because I wanted to be an author myself that I wrote iText.");
                doc.Add(a);

                //包含页码没有任何边框的页脚。
                iTextSharp.text.HeaderFooter footer = new iTextSharp.text.HeaderFooter(new Phrase("This is page: "), true);
                footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
                doc.Footer = footer;

                //Chapter对象和Section对象自动构建一个树:
                iTextSharp.text.Font f1 = new iTextSharp.text.Font();
                f1.SetStyle(iTextSharp.text.Font.BOLD);
                Paragraph cTitle = new Paragraph("This is chapter 1", f1);
                Chapter chapter = new Chapter(cTitle, 1);
                Paragraph sTitle = new Paragraph("This is section 1 in chapter 1", f1);
                Section section = chapter.AddSection(sTitle, 1);
                doc.Add(chapter);

                //构建了一个简单的表:
                Table aTable = new Table(4, 4);
                aTable.AutoFillEmptyCells = true;
                aTable.AddCell("2.2", new System.Drawing.Point(2, 2));
                aTable.AddCell("3.3", new System.Drawing.Point(3, 3));
                aTable.AddCell("2.1", new System.Drawing.Point(2, 1));
                aTable.AddCell("1.3", new System.Drawing.Point(1, 3));
                doc.Add(aTable);
                //构建了一个不简单的表:
                Table table = new Table(3);
                table.BorderWidth = 1;
                table.BorderColor = new iTextSharp.text.Color(0, 0, 255);
                table.Cellpadding = 5;
                table.Cellspacing = 5;
                Cell cell = new Cell("header");
                cell.Header = true;
                cell.Colspan = 3;
                table.AddCell(cell);
                cell = new Cell("example cell with colspan 1 and rowspan 2");
                cell.Rowspan = 2;
                cell.BorderColor = new iTextSharp.text.Color(255, 0, 0);
                table.AddCell(cell);
                table.AddCell("1.1");
                table.AddCell("2.1");
                table.AddCell("1.2");
                table.AddCell("2.2");
                table.AddCell("cell test1");
                cell = new Cell("big cell");
                cell.Rowspan = 2;
                cell.Colspan = 2;
                cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0);
                table.AddCell(cell);
                table.AddCell("cell test2");
                // 改变了单元格“big cell”的对齐方式:
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                doc.Add(table);

                #endregion
                //关闭document
                doc.Close();
                //打开PDF,看效果
                //Process.Start(sourcePath);
            }
            catch (DocumentException de)
            {
                Console.WriteLine(de.Message);
                Console.ReadKey();
            }
            catch (IOException io)
            {
                Console.WriteLine(io.Message);
                Console.ReadKey();
            }
        }