Beispiel #1
0
        private static void _add_to_table(Guid applicationId, HttpContext context, PdfPTable mainTable,
                                          StyleAttrCSSResolver cssResolver, WikiPDFText text, Font font, PdfPCell cell = null)
        {
            if (cell == null)
            {
                cell = new PdfPCell();
            }

            cell.Border = 0;
            cell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
            cell.RunDirection        = text.IsRTL ? PdfWriter.RUN_DIRECTION_RTL : PdfWriter.RUN_DIRECTION_LTR;
            cell.SetLeading(0, 2);

            itsXmlHtml.DefaultTagProcessorFactory tagProcessors =
                (itsXmlHtml.DefaultTagProcessorFactory)itsXmlHtml.Tags.GetHtmlTagProcessorFactory();

            tagProcessors.RemoveProcessor(itsXmlHtml.HTML.Tag.IMG);                                          // remove the default processor
            tagProcessors.AddProcessor(itsXmlHtml.HTML.Tag.IMG, new CustomImageTagProcessor(applicationId)); // use our new processor

            //tagProcessors.AddProcessor(itsXmlHtml.HTML.Tag.TABLE, new TableTagProcessor());

            HtmlPipelineContext htmlContext =
                new HtmlPipelineContext(new itsXmlHtml.CssAppliersImpl(new IranSansFontProvider(font)));

            htmlContext.SetImageProvider(new ImageProvider());
            htmlContext.CharSet(Encoding.UTF8);
            htmlContext.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);

            ElementsCollector   elementsHandler = new ElementsCollector();
            CssResolverPipeline pipeline        = new CssResolverPipeline(cssResolver,
                                                                          new HtmlPipeline(htmlContext, new ElementHandlerPipeline(elementsHandler, null)));

            itsXml.XMLWorker worker = new itsXml.XMLWorker(pipeline, parseHtml: true);
            XMLParser        parser = new XMLParser(true, worker, Encoding.UTF8);

            parser.Parse(new StringReader(text.Text));

            cell.AddElement(elementsHandler.Paragraph);
            mainTable.AddCell(cell);
        }
Beispiel #2
0
        private static List <WikiPDFText> convert_div_to_p(Guid applicationId, List <WikiPDFText> strHTMLParagraphs)
        {
            List <WikiPDFText> xmlParagraphs = new List <WikiPDFText>();

            //Tabdil hame tag haye div be tag p
            //ITextSharp Tag div nemishnase
            foreach (WikiPDFText s in strHTMLParagraphs)
            {
                bool forceRTL = s.ForceRTL;

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(("<p>" + s.Text + "</p>").ToXHtml());

                XmlNodeList xnl = doc.GetElementsByTagName("div");

                while (xnl.Count != 0)
                {
                    XmlNode    oldElem = xnl[0];
                    XmlElement newElem = doc.CreateElement("p");

                    while (oldElem.ChildNodes.Count != 0)
                    {
                        newElem.AppendChild(oldElem.ChildNodes[0]);
                    }
                    while (oldElem.Attributes.Count != 0)
                    {
                        newElem.Attributes.Append(oldElem.Attributes[0]);
                    }

                    oldElem.ParentNode.ReplaceChild(newElem, oldElem);
                }

                string toBeAdded = string.Empty;

                XmlNode firstChild = doc.LastChild.FirstChild;

                while (firstChild != null)
                {
                    if (firstChild.Name.ToLower() == "p")
                    {
                        if (!string.IsNullOrEmpty(toBeAdded))
                        {
                            WikiPDFText t = new WikiPDFText(applicationId, toBeAdded);
                            if (forceRTL)
                            {
                                t.set_is_rtl(true);
                            }
                            xmlParagraphs.Add(t);
                        }

                        WikiPDFText p = new WikiPDFText(applicationId, firstChild.OuterXml.ToString());

                        if (forceRTL || p.Text.StartsWith("<p dir=\"RTL\""))
                        {
                            p.set_is_rtl(true);
                        }

                        bool hasNothing = !string.IsNullOrEmpty(p.Text) && p.Text.Trim().ToLower().StartsWith("<p>") &&
                                          string.IsNullOrEmpty(firstChild.InnerXml.ToLower());

                        if (!hasNothing)
                        {
                            xmlParagraphs.Add(p);
                            toBeAdded = string.Empty;
                        }
                    }
                    else
                    {
                        toBeAdded += firstChild.OuterXml.ToString();
                    }

                    firstChild = firstChild.NextSibling;

                    if (firstChild == null && !string.IsNullOrEmpty(toBeAdded))
                    {
                        WikiPDFText t = new WikiPDFText(applicationId, toBeAdded);
                        if (forceRTL)
                        {
                            t.set_is_rtl(true);
                        }
                        xmlParagraphs.Add(t);
                    }
                }
            }

            return(xmlParagraphs);
        }
Beispiel #3
0
        public static byte[] export_as_pdf(Guid applicationId, Guid?currentUserId, bool isUser, DownloadedFileMeta meta,
                                           string title, string description, List <string> keywords, List <KeyValuePair <Guid, string> > wikiTitles,
                                           Dictionary <Guid, List <KeyValuePair <string, string> > > wikiParagraphs, Dictionary <string, string> metaData,
                                           List <string> authors, Guid?coverId, Guid?coverOwnerNodeId, string password, HttpContext context)
        {
            bool hasCustomCover = coverId.HasValue && coverOwnerNodeId.HasValue && currentUserId.HasValue;

            List <WikiPDFText> wikiCover = hasCustomCover ? new List <WikiPDFText>() :
                                           get_default_cover(applicationId, isUser, title, metaData, authors);

            string strKeywords = string.Join(" - ", keywords);

            WikiPDFText wikiTitle = new WikiPDFText(applicationId,
                                                    @"<br><br><p style='text-align:center;'><strong><span style='color:DarkSlateGray;'>" + title + "</span></strong></p><br><br>");
            List <WikiPDFText> wikiDesc = convert_div_to_p(applicationId, new List <WikiPDFText>()
            {
                new WikiPDFText(applicationId,
                                string.IsNullOrEmpty(description) ? "" : @"<br><p class='NodeAbs'>" + description + "</p><br>")
            });
            WikiPDFText wikiKeywords = new WikiPDFText(applicationId,
                                                       string.IsNullOrEmpty(strKeywords) ? "" : @"<br><p> " + strKeywords + " </p><br>");

            string      pdfTitles     = string.Empty;
            WikiPDFText wikiPDFTitles = null;

            List <WikiPDFText> strHTMLParagraphs = new List <WikiPDFText>();

            foreach (KeyValuePair <Guid, string> t in wikiTitles)
            {
                if (!wikiParagraphs.ContainsKey(t.Key) || wikiParagraphs[t.Key].Count == 0)
                {
                    continue;
                }

                bool hasTitle = !string.IsNullOrEmpty(t.Value);

                int counter = 0;

                if (hasTitle)
                {
                    pdfTitles += "<p><a href='#" + t.Key.ToString() + "'>" + t.Value + "</a></p><br>";
                    pdfTitles += ProviderUtil.list_to_string <string>(wikiParagraphs[t.Key].Where(
                                                                          u => !string.IsNullOrEmpty(u.Key) && !string.IsNullOrEmpty(u.Value)).Select(
                                                                          p => "<p><a style='color:gray;' href='#" + t.Key.ToString() + (++counter).ToString() + "'>" + p.Key + "</a></p><br>").ToList <string>(), ' ');
                }

                wikiPDFTitles = new WikiPDFText(applicationId, pdfTitles);

                counter = 0;

                WikiPDFText mt = !hasTitle ? null : new WikiPDFText(applicationId,
                                                                    @"<br><a name='" + t.Key.ToString() + "'><strong style='color:#00a;'>" + t.Value + "</strong></a>");

                List <KeyValuePair <string, string> > prgrs = wikiParagraphs[t.Key].Where(
                    u => !string.IsNullOrEmpty(u.Value)).Select(x => x).ToList();

                WikiPDFText tempParagraphs = new WikiPDFText(applicationId,
                                                             ProviderUtil.list_to_string <string>(prgrs.Select(u => u.Value).ToList(), ' '));
                if (mt != null && tempParagraphs.IsProbablyRTL)
                {
                    mt.set_is_rtl(true);
                }

                if (mt != null)
                {
                    strHTMLParagraphs.Add(mt);
                }

                foreach (KeyValuePair <string, string> kvp in prgrs)
                {
                    WikiPDFText pp = new WikiPDFText(applicationId, kvp.Value);

                    if (!string.IsNullOrEmpty(kvp.Key))
                    {
                        WikiPDFText pt = new WikiPDFText(applicationId, "<p><a style='color:#444;' name='" +
                                                         t.Key.ToString() + (++counter).ToString() + "'><strong>" + kvp.Key + "</strong></a></p>");

                        if (pp.IsProbablyRTL)
                        {
                            pt.set_is_rtl(true);
                        }

                        strHTMLParagraphs.Add(pt);
                    }

                    strHTMLParagraphs.Add(pp);
                }
            }

            strHTMLParagraphs = convert_div_to_p(applicationId, strHTMLParagraphs);

            using (MemoryStream mem = new MemoryStream())
            {
                using (Document pdfDoc = new Document(PageSize.A4))
                {
                    BaseFont baseFont = BaseFont.CreateFont(
                        PublicMethods.map_path("~/Fonts/windows/IRANSans.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    Font font = new Font(baseFont, size: 9);

                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, mem);

                    PageEventHelper pageEvents = new PageEventHelper(applicationId, title, font, meta);
                    pdfWriter.PageEvent = pageEvents;

                    pdfWriter.RgbTransparencyBlending = true;
                    pdfDoc.Open();

                    StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver();
                    cssResolver.AddCssFile(PublicMethods.map_path("~/CSS/pdf.css"), true);

                    PdfPTable mainTable = new PdfPTable(1)
                    {
                        WidthPercentage = 100,
                        RunDirection    = PdfWriter.RUN_DIRECTION_RTL
                    };

                    mainTable.SplitLate = false;

                    PdfPCell coverCell = new PdfPCell()
                    {
                        FixedHeight         = 750,
                        RunDirection        = PdfWriter.RUN_DIRECTION_RTL,
                        HorizontalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell titlesCell = new PdfPCell
                    {
                        Border              = 0,
                        RunDirection        = PdfWriter.RUN_DIRECTION_RTL,
                        HorizontalAlignment = Element.ALIGN_RIGHT,
                        PaddingRight        = 20f,
                        PaddingLeft         = 20f,
                        BackgroundColor     = BaseColor.LIGHT_GRAY
                    };

                    for (int c = 0; c < wikiCover.Count; c++)
                    {
                        _add_to_table(applicationId, context, mainTable, cssResolver, wikiCover[c], font, coverCell);
                    }
                    //_add_to_table(applicationId, context, mainTable, cssResolver, wikiTitle, font);
                    if (!string.IsNullOrEmpty(description))
                    {
                        for (int c = 0; c < wikiDesc.Count; c++)
                        {
                            _add_to_table(applicationId, context, mainTable, cssResolver, wikiDesc[c], font);
                        }
                    }
                    if (!string.IsNullOrEmpty(strKeywords))
                    {
                        _add_to_table(applicationId, context, mainTable, cssResolver, wikiKeywords, font);
                    }
                    //_add_to_table(applicationId, context, mainTable, cssResolver, wikiPDFTitles, font, titlesCell);
                    for (int c = 0; c < strHTMLParagraphs.Count; c++)
                    {
                        _add_to_table(applicationId, context, mainTable, cssResolver, strHTMLParagraphs[c], font);
                    }

                    pdfDoc.Add(mainTable);

                    pdfDoc.Close();

                    byte[] finalContent = mem.ToArray();

                    if (hasCustomCover)
                    {
                        finalContent = add_custom_cover(applicationId,
                                                        currentUserId.Value, finalContent, coverId.Value, coverOwnerNodeId.Value);
                    }

                    return(string.IsNullOrEmpty(password) ? finalContent : PDFUtil.set_password(finalContent, password));
                }
            }
        }