Пример #1
0
        public static void CreatePDF(System.IO.Stream stream, string htmlMarkup)
        {
            if (null == stream || string.IsNullOrEmpty(htmlMarkup))
            {
                return;
            }

            System.IO.MemoryStream m        = new System.IO.MemoryStream();
            iText.Document         document = new iText.Document();
            iText.pdf.PdfWriter    writer   = iText.pdf.PdfWriter.GetInstance(document, m);

            HTMLDocument pseudoDoc = new HTMLDocument();

            ((IHTMLDocument2)pseudoDoc).write(htmlMarkup);

            document.Open();

            IHTMLElementCollection children = (IHTMLElementCollection)pseudoDoc.getElementById("pdfContainer").children;

            foreach (IHTMLElement el in children)
            {
                IHTMLElement theEl = el;

                if (null == theEl.className)
                {
                    continue;
                }

                string className = theEl.className.ToLowerInvariant();

                if (className == "ignore" || string.IsNullOrEmpty(className))
                {
                    continue;
                }

                string tagName = theEl.tagName.ToLowerInvariant();

                string innerText = theEl.innerText;

                if (string.IsNullOrEmpty(innerText))
                {
                    theEl     = (IHTMLElement)((IHTMLElementCollection)el.children).item(null, 0);
                    tagName   = theEl.tagName.ToLowerInvariant();
                    innerText = theEl.innerText;
                }

                if (tagName == "div" || tagName == "span")
                {
                    document.Add(new iText.Paragraph(innerText));
                    continue;
                }

                if (tagName == "hr")
                {
                    if (className == "pagebreak")
                    {
                        document.NewPage();
                    }
                    else
                    {
                        iText.pdf.PdfPTable t = new iText.pdf.PdfPTable(1);
                        t.HorizontalAlignment             = iText.Element.ALIGN_CENTER;
                        t.WidthPercentage                 = 100f; // this would be the 100 from setHorizontalLine
                        t.SpacingAfter                    = 5f;
                        t.SpacingBefore                   = 0f;
                        t.DefaultCell.UseVariableBorders  = true;
                        t.DefaultCell.VerticalAlignment   = iText.Element.ALIGN_MIDDLE;
                        t.DefaultCell.HorizontalAlignment = iText.Element.ALIGN_CENTER;
                        t.DefaultCell.Border              = iText.Image.BOTTOM_BORDER; // This generates the line
                        t.DefaultCell.BorderWidth         = 1f;                        // this would be the 1 from setHorizontalLine
                        t.DefaultCell.Padding             = 0;
                        t.AddCell("");
                        document.Add(t);
                    }
                }

                if (tagName == "img")
                {
                    iText.Image img = iText.Image.GetInstance(theEl.getAttribute("src", 0).ToString());
                    img.ScaleToFit(document.PageSize.Width - 100, document.PageSize.Height - 100);
                    document.Add(img);
                    continue;
                }
            }

            pseudoDoc.close();
            pseudoDoc = null;

            document.Close();

            writer.Flush();

            byte[] data = m.GetBuffer();

            try
            {
                stream.Write(data, 0, data.Length);
                stream.Flush();
                stream.Close();
            }
            catch
            {
                throw;
            }
            finally
            {
                Array.Clear(data, 0, data.Length);
                data     = null;
                document = null;
                writer   = null;
                m.Dispose();
                m = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Пример #2
0
        /// <summary>Converts the Tif files into a multi page PDF multiple.</summary>
        /// <param name="sourceDir">The source dir.</param>
        /// <param name="destinationDir">The destination dir.</param>
        /// <exception cref="System.Exception">Source folder '"+ sourceDir + "' contains no files!!!</exception>
        private static void ConvertMultiple(string sourceDir, string destinationDir)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(sourceDir);

                int totalFiles = di.GetFiles().Length;
                if (totalFiles == 0)
                {
                    throw new System.Exception("Source folder '" + sourceDir + "' contains no files!!!");
                }
                Console.WriteLine("Total Files in Source Folder = " + totalFiles);

                foreach (var file in di.GetFiles())
                {
                    totalFiles = totalFiles -= 1;

                    if (file.Extension.ToString() == ".tif" || file.Extension.ToString() == ".tiff")
                    {
                        iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
                        string     fileName                  = Path.GetFileNameWithoutExtension(file.ToString());
                        string     filePath                  = string.Format("{0}\\{1}.{2}", destinationDir, fileName, "pdf");
                        string     sourceFilePath            = string.Format("{0}\\{1}.{2}", sourceDir, fileName, "tif");
                        FileStream fs                        = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
                        iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs);

                        // Counts the files remaining to be converting
                        Console.WriteLine("Converting: " + file.Name + " Total Files Left: " + totalFiles);

                        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(sourceFilePath);

                        document.Open();
                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                        int total = bmp.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
                        for (int k = 0; k < total; ++k)
                        {
                            bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Bmp);

                            // Scale the image to fit in the page
                            img.ScalePercent(72f / img.DpiX * 100);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }

                        bmp.Dispose();
                        writer.Flush();
                        document.Close();
                        document.Dispose();
                    }
                    else
                    {
                        Console.WriteLine("Not Converting: " + file.Name + " Total Files Left: " + totalFiles);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }