Exemplo n.º 1
0
        /// <summary>
        /// 返回页数 PdfReader
        /// </summary>
        /// <param name="outMergeFile"></param>
        /// <returns></returns>
        public int MergePDFFilesPages(string outMergeFile)
        {
            int       page = 0;
            PdfReader reader;

            try
            {
                using (iTextSharp.text.Document document = new iTextSharp.text.Document())
                {
                    if (File.Exists(outMergeFile))
                    {
                        reader = new PdfReader(outMergeFile);
                        if (reader != null)
                        {
                            page = reader.NumberOfPages;
                            reader.Close();
                            reader.Dispose();
                        }
                    }
                    document.Close();
                    document.Dispose();

                    File.SetAttributes(outMergeFile, FileAttributes.Normal);
                }

                return(page);
            }
            catch (Exception ex)
            {
                MyCommon.WriteLog("取PDF页数报错" + ex.Message);
                return(page);
            }
        }
Exemplo n.º 2
0
        private void SavePdf(string inputPath, string pathSaveFile)
        {
            // Create a new PDF document
            var doc  = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
            var fs   = new FileStream(pathSaveFile, FileMode.Create);
            var wPdf = PdfWriter.GetInstance(doc, fs);

            doc.Open();

            if (File.Exists(inputPath))
            {
                //se arquivo unico
                var img = iTextSharp.text.Image.GetInstance(inputPath);

                doc.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height));
                doc.NewPage();

                img.SetAbsolutePosition(0, 0);
                wPdf.DirectContent.AddImage(img);
            }
            else
            {
                var imageFiles = Directory.GetFiles(inputPath, "*.*"); //.Where(f => fileExtensions.Contains(Path.GetExtension(f).ToLower()));
                //Array.Sort(imageFiles.ToArray(), new AlphanumComparatorFast());

                //importing the images in the pdf
                foreach (string imageFile in imageFiles)
                {
                    //checking file extension
                    //string ext = Path.GetExtension(imageFile).ToLower();
                    //if ((string.Compare(ext, ".jpg") == 0) || (string.Compare(ext, ".jpeg") == 0) || (string.Compare(ext, ".png") == 0) || (string.Compare(ext, ".bmp") == 0) || (string.Compare(ext, ".new") == 0))
                    //{
                    var img = iTextSharp.text.Image.GetInstance(imageFile);

                    doc.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height));
                    doc.NewPage();

                    img.SetAbsolutePosition(0, 0);
                    wPdf.DirectContent.AddImage(img);
                    //}
                }
            }

            //save file
            doc.Close();
            doc.Dispose();

            fs.Close();
            fs.Dispose();

            wPdf.Close();
            wPdf.Dispose();
        }
Exemplo n.º 3
0
 private void freePDF()
 {
     if (avaPDF)
     {
         try {
             pdfReader.Dispose();
             pdfDoc.Dispose();
             pdfCopy.Dispose();
         } catch {
             pdfReader = null;
             pdfDoc    = null;
             pdfCopy   = null;
         }
     }
 }
Exemplo n.º 4
0
        // TODO: Can code lai
        public void SaveByMemoryStream(string fileName)
        {
            string defaultFontPath = FontUtils.GetFontPath(ReportFactory.FontList, ReportFactory.FontStyle);

            iTextSharp.text.FontFactory.Register(defaultFontPath);

            byte[] data;
            using (var memoryStream = new MemoryStream())
            {
                PageSize currentPageSize = PageSize ?? ReportFactory.PageSize;

                iTextSharp.text.Rectangle pageSize = PageSizeUtils.ToRectangle(currentPageSize);
                var document = new iTextSharp.text.Document(pageSize, 10, 10, 10, 10);
                var writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                foreach (var paragraph in Paragraphs)
                {
                    if (paragraph is Table)
                    {
                        iTextSharp.text.pdf.PdfPTable tableSource = paragraph as Table;
                        document.Add(tableSource);
                    }
                    else if (paragraph is Paragraph)
                    {
                    }
                }

                document.Close();
                document.Dispose();

                data = memoryStream.ToArray();
            }

            File.WriteAllBytes(fileName, data);
        }
Exemplo n.º 5
0
        /// <summary>
        /// 打印PDF
        /// </summary>
        public void PrintPDF()
        {
            m_doc    = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(0, 0, PaperSize.Width * 100 / 25.4F * m_rate, PaperSize.Height * 100 / 25.4F * m_rate));
            m_stream = new System.IO.MemoryStream();
            m_write  = iTextSharp.text.pdf.PdfWriter.GetInstance(m_doc, m_stream);
            m_doc.OpenDocument();

            PrintPDFPage();

            m_doc.Close();
            m_stream.Flush();
            //输出到文件

            using (var fs = new System.IO.FileStream(PrintFileName, System.IO.FileMode.Create))
            {
                var bs = m_stream.GetBuffer();
                fs.Write(bs, 0, bs.Length);
                fs.Flush();
                m_stream.Dispose();
                m_stream = null;
                m_doc.Dispose();
                m_doc = null;
            }
        }
Exemplo n.º 6
0
        public void SaveImage(HttpContext context)
        {
            var aa = context.Request.Form["svg"];

            if (context.Request.Form["svg"] != null)
            {
                string tType     = "image/png";
                string tSvg      = context.Request.Form["svg"].ToString();
                string tFileName = "";

                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                tFileName = rand.Next().ToString();

                MemoryStream tData = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));

                MemoryStream tStream = new MemoryStream();
                string       tTmp    = new Random().Next().ToString();

                string tExt        = "";
                string tTypeString = "";

                switch (tType)
                {
                case "image/png":
                    tTypeString = "-m image/png";
                    tExt        = "png";
                    break;

                case "image/jpeg":
                    tTypeString = "-m image/jpeg";
                    tExt        = "jpg";
                    break;

                case "application/pdf":
                    tTypeString = "-m application/pdf";
                    tExt        = "pdf";
                    break;

                case "image/svg+xml":
                    tTypeString = "-m image/svg+xml";
                    tExt        = "svg";
                    break;
                }

                if (tTypeString != "")
                {
                    //string tWidth = context.Request.Form["width"].ToString();
                    //string tWidth = "0";
                    Svg.SvgDocument tSvgObj = SvgDocument.Open(tData);
                    switch (tExt)
                    {
                    case "jpg":
                        tSvgObj.Draw().Save(tStream, ImageFormat.Jpeg);
                        break;

                    case "png":

                        tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                        break;

                    case "pdf":
                        PdfWriter tWriter = null;
                        iTextSharp.text.Document tDocumentPdf = null;
                        try
                        {
                            tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                            tDocumentPdf = new iTextSharp.text.Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));
                            tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);
                            iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(tStream.ToArray());
                            tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                            tStream = new MemoryStream();
                            tWriter = PdfWriter.GetInstance(tDocumentPdf, tStream);
                            tDocumentPdf.Open();
                            tDocumentPdf.NewPage();
                            tDocumentPdf.Add(tGraph);
                            tDocumentPdf.CloseDocument();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            tDocumentPdf.Close();
                            tDocumentPdf.Dispose();
                            tWriter.Close();
                            tWriter.Dispose();
                            tData.Dispose();
                            tData.Close();
                        }
                        break;

                    case "svg":
                        tStream = tData;
                        break;
                    }
                    System.IO.MemoryStream ms    = new System.IO.MemoryStream(tStream.ToArray());
                    System.Drawing.Image   image = System.Drawing.Image.FromStream(ms);
                    string savePath = context.Server.MapPath("image/");

                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }
                    savePath += tFileName + "." + tExt;
                    string SavePathImage = tFileName + "." + tExt;
                    context.Session["FirstImage"] = savePath;
                    image.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
                    image.Dispose();
                    context.Response.Write(tFileName + "." + tExt);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 返回页数
        /// </summary>
        /// <param name="FileList"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public int MergePDF(string[] FileList, string FileName)
        {
            if (System.IO.File.Exists(FileName))
            {
                System.IO.File.Delete(FileName);
            }
            int iPageCount = 0;

            if (FileList.Length == 1)
            {
                System.IO.File.Copy(FileList[0], FileName, true);

                /*
                 * 修改人:侯波
                 * 修改时间:2017-04-12
                 * 描述:拖入一页电子文件计算页数
                 */
                if (File.Exists(FileName))
                {
                    try
                    {
                        PdfReader reader1;
                        reader1 = new PdfReader(FileName);
                        if (reader1 != null)
                        {
                            iPageCount = reader1.NumberOfPages;
                            reader1.Close();
                            reader1.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        MyCommon.WriteLog("Cell2 MergeMultiPdf合并PDF异常:" + ex.Message);
                    }
                }
            }
            else
            {
                try
                {
                    #region 金格合并
                    //List<Stream> FSList = new List<Stream>();
                    //foreach (string file_pdf in FileList)
                    //{
                    //    FSList.Add(new FileStream(file_pdf, FileMode.Open));
                    //}
                    //using (FileStream os = new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite))
                    //{
                    //    com.kinggrid.pdf.KGPdfHummerUtils.MergeMultiPdf(FSList, os);
                    //    if (System.IO.File.Exists(FileName))
                    //    {
                    //        iPageCount = MergePDFFilesPages(FileName);
                    //    }
                    //    else
                    //    {
                    //        MyCommon.WriteLog("合并PDF错误");
                    //    }
                    //}
                    #endregion

                    PdfReader reader;
                    using (iTextSharp.text.Document document = new iTextSharp.text.Document())
                    {
                        PdfImportedPage newPage;
                        PdfCopy         copy = new PdfCopy(document, (new FileStream(FileName, FileMode.Create)));
                        document.Open();
                        for (int i = 0; i < FileList.Length; i++)
                        {
                            reader = new PdfReader(FileList[i], null, true);
                            int iPageNum = reader.NumberOfPages;
                            for (int j = 1; j <= iPageNum; j++)
                            {
                                document.NewPage();
                                newPage = copy.GetImportedPage(reader, j);
                                copy.AddPage(newPage);
                            }
                            reader.Close();
                            reader.Dispose();
                        }
                        document.Close();
                        document.Dispose();
                        if (File.Exists(FileName))
                        {
                            reader = new PdfReader(FileName);
                            if (reader != null)
                            {
                                iPageCount = reader.NumberOfPages;
                                reader.Close();
                                reader.Dispose();
                            }
                        }
                        copy.Close();
                        copy.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    MyCommon.WriteLog("Cell2 MergeMultiPdf合并PDF异常:" + ex.Message);
                }
            }
            return(iPageCount);
        }
Exemplo n.º 8
0
        // Сохраняет выделенные файлы в PDF
        private void btnPDF_Click(object sender, EventArgs e)
        {
            if (0 == listView1.SelectedItems.Count)
            {
                return;
            }

            bool deleteFiles = chkDeleteFiles.Checked;             // Удалять jpeg'и после создания pdf

            savePDFDialog.Filter           = "Файлы PDF|*.pdf";
            savePDFDialog.InitialDirectory = PDFInitialDir;
            if (DialogResult.OK != savePDFDialog.ShowDialog())
            {
                return;
            }

            Cursor.Current = Cursors.WaitCursor;

            int s = 0;

            if (radioImageMagick.Checked)
            {
                MagickImageCollection images = new MagickImageCollection();
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    images.Add(scanFileNames[item.Index]);
                    images[s++].Strip();                     // Иначе PDF может получиться кривой с ошибкой insufficient data for an image
                }
                try
                {
                    images.Write(savePDFDialog.FileName, MagickFormat.Pdf);
                }
                catch (MagickException me)
                {
                    toolStripStatus.Text = me.Message;
                    deleteFiles          = false;
                }
                images.Dispose();
            }

            if (radioiTextSharp.Checked)
            {
                iTextSharp.text.Document document = new iTextSharp.text.Document();
                FileStream fileStream             = new FileStream(savePDFDialog.FileName, FileMode.Create);
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, fileStream);
                document.Open();
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(scanFileNames[item.Index]);
                    image.SetAbsolutePosition(0.0f, 0.0f);
                    image.ScaleToFit(image.Width / image.DpiX * 72f, image.Height / image.DpiY * 72f);
                    iTextSharp.text.Chunk chunk = new iTextSharp.text.Chunk();
                    chunk.SetNewPage();
                    if (s > 0)
                    {
                        document.Add(chunk);
                    }
                    if (deleteFiles & !document.Add(image))
                    {
                        deleteFiles = false;
                    }
                    chunk = null;
                    image = null;
                    s++;
                }

                document.Close();
                document.Dispose();
                fileStream.Close();
                fileStream.Dispose();
            }

            if (deleteFiles)
            {
                btnDelete_Click(btnPDF, null);
            }

            Cursor.Current = Cursors.Default;
        }
Exemplo n.º 9
0
      //  public List<Card> Cards { get; set; }


        public void tiffToPDF(string resultPDF)
        {
            // creation of the document with a certain size and certain margins  
            using (iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0))
            {
                using (FileStream fs = new System.IO.FileStream(resultPDF, System.IO.FileMode.Create))
                {
                    // creation of the different writers  
                    using (iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs))
                    {

                        document.Open();
                        foreach (Page page in Pages)
                        {
                            if (page.Card.ImageLocationLR != null)
                            {
                                // load the tiff image and count the total pages  

                                int total = 0;
                                using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(page.Card.ImageLocationLR))
                                {
                                     total = bm2.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
                                    // bm2 = null;
                                    bm2.Dispose();
                                }
                                   



                                    for (int k = 0; k < total; ++k)
                                    {
                                        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(page.Card.ImageLocationLR);
                                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                                        bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                                        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);


                                        img.ScaleToFitHeight = false;

                                        img.ScalePercent(70f / img.DpiX * 100);

                                        // scale the image to fit in the page  
                                     //Lukas old value   img.SetAbsolutePosition(-22, 25);
                                       img.SetAbsolutePosition(0, 0);


                                        cb.AddImage(img);

                                        document.NewPage();

                                        img = null;
                                        
                                        cb.ClosePath();
                                        bm.Dispose();
                                    }

                                   
                                  
                                
                            }
                        }

                      

                        document.Close();
                        document.Dispose();
                        writer.Dispose();
                       
                        fs.Close();
                        fs.Dispose();

                    }
                }
            }
        }