Esempio n. 1
0
        public PdfDocument(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            _path = path;

            _document.LoadPDF(path);
        }
Esempio n. 2
0
        public bool LoadStream(System.IO.Stream fileStream)
        {
            if (_pdfDoc != null)
            {
                _pdfDoc.Dispose();
                _pdfDoc = null;
            }
            //if (_pdfDoc == null)
            //{
            _pdfDoc = new PDFWrapper();
            _pdfDoc.RenderNotifyFinished += new RenderNotifyFinishedHandler(_pdfDoc_RenderNotifyFinished);
            _pdfDoc.PDFLoadCompeted      += new PDFLoadCompletedHandler(_pdfDoc_PDFLoadCompeted);
            _pdfDoc.PDFLoadBegin         += new PDFLoadBeginHandler(_pdfDoc_PDFLoadBegin);

            try
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                //fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
                //return pdfDoc.LoadPDF(fs);
                bool bRet = _pdfDoc.LoadPDF(fileStream);
                return(bRet);
            }
            catch (System.Security.SecurityException ex)
            {
                frmPassword frm = new frmPassword();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (!frm.UserPassword.Equals(String.Empty))
                    {
                        _pdfDoc.UserPassword = frm.UserPassword;
                    }
                    if (!frm.OwnerPassword.Equals(String.Empty))
                    {
                        _pdfDoc.OwnerPassword = frm.OwnerPassword;
                    }
                    bool bRet = _pdfDoc.LoadPDF(fileStream);
                    return(bRet);
                }
                else
                {
                    throw ex;
                }
            }
        }
Esempio n. 3
0
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
        {
            PDFWrapper pdfWrapper = new PDFWrapper();

            pdfWrapper.LoadPDF(pdfInputPath);
            if (!System.IO.Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }
            // validate pageNum
            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }
            if (endPageNum > pdfWrapper.PageCount)
            {
                endPageNum = pdfWrapper.PageCount;
            }
            if (startPageNum > endPageNum)
            {
                int tempPageNum = startPageNum;
                startPageNum = endPageNum;
                endPageNum   = startPageNum;
            }
            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                pdfWrapper.ExportJpg(imageOutputPath + imageName, i, i, 300, 90);//这里可以设置输出图片的页数、大小和图片质量从默认的150--》300
                while (pdfWrapper.IsJpgBusy == true)
                {
                    System.Threading.Thread.Sleep(500);
                }
            }
            pdfWrapper.Dispose();
        }
Esempio n. 4
0
        public static void ConvertPDFtoJPG(string name)
        {
            using (var fs = new FileStream(name, FileMode.OpenOrCreate))
            {
                var _pdfDoc = new PDFWrapper();
                _pdfDoc.LoadPDF(fs);

                for (int i = 0; i < _pdfDoc.PageCount; i++)
                {
                    var fileName = Path.Combine(Path.GetDirectoryName(name).Replace(@"D:\temp\New folder\", ""), $"{Path.GetFileNameWithoutExtension(name)}-page-{i + 1}.jpg");

                    Image img = RenderPage(_pdfDoc, i);
                    var   tn  = img.GetThumbnailImage(150, 200, () => { return(true); }, IntPtr.Zero);
                    using (var ms = new MemoryStream())
                    {
                        tn.Save(ms, ImageFormat.Jpeg);
                        ms.Seek(0, SeekOrigin.Begin);
                        SCS(ms, fileName, i);
                    }
                    Console.WriteLine($"saved: {fileName}");
                }
                Console.WriteLine(name);
                _pdfDoc.Dispose();
            }
        }
        /// <summary>
        /// This method processes an uncompressed Adobe (text) object
        /// and extracts text.
        /// </summary>
        /// <param name="input">uncompressed</param>
        /// <returns></returns>
        private void ExtractTextFromPDFBytes(byte[] input)
        {
            var        f  = new FileInfo("c:\\MyTest.pdf");
            FileStream fs = f.Create();

            fs.Write(input, 0, input.Count());
            fs.Close();

            _pdfDoc.LoadPDF("c:\\MyTest.pdf");

            f.Delete();
            OutTexts();

            PdfParsed();
        }
Esempio n. 6
0
 public bool ShowFile(string path)
 {
     try
     {
         doc.LoadPDF(path);
         FitWidght();
         doc.RenderPage(pageViewer1.Handle, true);
         RenderFinish();
         pageViewer1.BringToFront();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 7
0
        public static void PdfFileToText(string srcFileName, string dstFileName)
        {
            var sb = new StringBuilder();
            using (var doc = new PDFWrapper())
            {
                doc.LoadPDF(srcFileName);

                PDFPage pg;
                for (int j = 1; j <= doc.PageCount; j++)
                {
                    pg = doc.Pages[j];
                    sb.Append(pg.Text);
                }
            }

            using (var sw = new StreamWriter(dstFileName, false, Encoding.Unicode))
            {
                sw.Write(sb.ToString());
            }
        }
Esempio n. 8
0
 /// <summary>
 /// pdf分页转图片
 /// </summary>
 /// <param name="attachmentId">附件id</param>
 /// <param name="sourcePath">文件原始路劲</param>
 /// <param name="fileInputPath">文件路劲(临时文件路劲)</param>
 /// <param name="fileSavePath">文件要保存的路劲</param>
 /// <param name="imageFormat">图片格式</param>
 /// <param name="DPI">图片分辨率(数值越大质量越高)</param>
 /// <param name="definition">清晰度(数值越大质量越高)</param>
 /// <returns></returns>
 public bool PdfToImg(int attachmentId, string sourcePath, string fileInputPath, string fileSavePath, ImageFormat imageFormat, int DPI, int definition)
 {
     try
     {
         List <int> list    = new List <int>();
         PDFWrapper wrapper = new PDFWrapper();
         wrapper.LoadPDF(fileInputPath);
         if (!Directory.Exists(fileSavePath))
         {
             Directory.CreateDirectory(fileSavePath);
         }
         var           pageCount = wrapper.PageCount;
         StringBuilder sb        = new StringBuilder();
         if (pageCount > 0)
         {
             sb.Append(string.Format("delete from PreviewFile where AttachmentId={0};", attachmentId));
             for (int num = 1; num <= pageCount; num++)
             {
                 string filename = fileSavePath + "\\" + num.ToString() + "." + imageFormat.ToString();
                 if (File.Exists(filename))
                 {
                     File.Delete(filename);
                 }
                 wrapper.ExportJpg(filename, num, num, (double)DPI, definition);
                 sb.Append(string.Format("insert into PreviewFile(AttachmentId,SavePath,CreateTime)values({0},'{1}','{2}');", attachmentId, fileSavePath.Replace(sourcePath, "").Replace("\\", "/"), DateTime.Now));
                 Thread.Sleep(1000);
             }
             wrapper.Dispose();
             var result = SqlHelper.ExecteNonQueryText(sb.ToString(), null);
             return(result > 0);
         }
         else
         {
             return(true);
         }
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
Esempio n. 9
0
        public static void PdfFileToText(string srcFileName, string dstFileName)
        {
            var sb = new StringBuilder();

            using (var doc = new PDFWrapper())
            {
                doc.LoadPDF(srcFileName);

                PDFPage pg;
                for (int j = 1; j <= doc.PageCount; j++)
                {
                    pg = doc.Pages[j];
                    sb.Append(pg.Text);
                }
            }

            using (var sw = new StreamWriter(dstFileName, false, Encoding.Unicode))
            {
                sw.Write(sb.ToString());
            }
        }
        /// <summary>
        /// 将PDF文档转换为图片的方法
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">生成图片的名字</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
        {
            PDFWrapper pdfWrapper = new PDFWrapper();

            pdfWrapper.LoadPDF(pdfInputPath);

            if (!System.IO.Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }

            // validate pageNum
            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }

            if (endPageNum > pdfWrapper.PageCount)
            {
                endPageNum = pdfWrapper.PageCount;
            }

            if (startPageNum > endPageNum)
            {
                int tempPageNum = startPageNum;
                startPageNum = endPageNum;
                endPageNum = startPageNum;
            }

            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                pdfWrapper.ExportJpg(imageOutputPath + imageName + i.ToString() + ".jpg", i, i, 150, 90);//这里可以设置输出图片的页数、大小和图片质量
                if (pdfWrapper.IsJpgBusy) { System.Threading.Thread.Sleep(50); }
            }

            pdfWrapper.Dispose();
        }
Esempio n. 11
0
        /// <summary>
        /// Loads a pdf file.
        /// </summary>
        /// <param name="cfile"></param>
        /// <returns></returns>
        public bool LoadPdf(string cfile)
        {
            UnloadPdf();
            mypdfDoc = new PDFLibNet.PDFWrapper();


            mypdfDoc.UseMuPDF = true;

            if (!File.Exists(cfile))
            {
                return(false);
            }
            //this line creates a handle
            //it can be closed with Dispose()
            Stopwatch s = new Stopwatch();
            //s.Start();
            bool ret = mypdfDoc.LoadPDF(cfile);

            // s.Stop();
            // MainWindow.AddStatusLine("LoadPDF took " + s.ElapsedMilliseconds + " ms");
            return(ret);
        }
Esempio n. 12
0
        /// <summary>
        /// 调用PDFLibNet生成图片(如果pdf文件有特殊字体,无法转化)
        /// </summary>
        private static void GetImgFromPDFLibNet()
        {
            string      pdfInputPath = AppDomain.CurrentDomain.BaseDirectory + "test.pdf";
            string      imageOutputPath = AppDomain.CurrentDomain.BaseDirectory + @"\Pdf2Img\";
            ImageFormat imageFormat = ImageFormat.Png;
            int         DPI = 200; int definition = 30;

            try
            {
                List <int> list    = new List <int>();
                PDFWrapper wrapper = new PDFWrapper();
                wrapper.LoadPDF(pdfInputPath);
                if (!Directory.Exists(imageOutputPath))
                {
                    Directory.CreateDirectory(imageOutputPath);
                }
                if (list.Count == 0)
                {
                    for (int i = 1; i <= wrapper.PageCount; i++)
                    {
                        list.Add(i);
                    }
                }
                foreach (int num in list)
                {
                    string filename = imageOutputPath + num.ToString() + "." + imageFormat.ToString();

                    wrapper.ExportJpg(filename, num, num, (double)DPI, definition);
                    Thread.Sleep(1000);
                    Console.WriteLine("生成图片" + filename);
                }
                wrapper.Dispose();
            }
            catch (Exception exception)
            {
                Console.WriteLine("异常" + exception.ToString());
            }
        }
Esempio n. 13
0
        public bool LoadStream(System.IO.Stream fileStream)
        {
            if (_pdfDoc != null)
            {
                _pdfDoc.Dispose();
                _pdfDoc = null;
            }
            //if (_pdfDoc == null)
            //{
            _pdfDoc = new PDFWrapper();
            _pdfDoc.RenderNotifyFinished += new RenderNotifyFinishedHandler(_pdfDoc_RenderNotifyFinished);
            _pdfDoc.PDFLoadCompeted += new PDFLoadCompletedHandler(_pdfDoc_PDFLoadCompeted);
            _pdfDoc.PDFLoadBegin += new PDFLoadBeginHandler(_pdfDoc_PDFLoadBegin);
            _pdfDoc.UseMuPDF = tsbUseMuPDF.Checked;

            try
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                //Does not supported by MuPDF.                
                //fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);                
                //return pdfDoc.LoadPDF(fs);                
                bool bRet = _pdfDoc.LoadPDF(fileStream);
                tsbUseMuPDF.Checked = _pdfDoc.UseMuPDF;
                return bRet;
            }
            catch (System.Security.SecurityException ex)
            {
                frmPassword frm = new frmPassword();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (!frm.UserPassword.Equals(String.Empty))
                        _pdfDoc.UserPassword = frm.UserPassword;
                    if (!frm.OwnerPassword.Equals(String.Empty))
                        _pdfDoc.OwnerPassword = frm.OwnerPassword;
                    bool bRet = _pdfDoc.LoadPDF(fileStream);
                    tsbUseMuPDF.Checked = _pdfDoc.UseMuPDF;
                    return bRet;
                }
                else
                {
                    throw ex;
                }
            }
                            
        }
Esempio n. 14
0
        public void makeSecure(BackgroundWorker worker)
        {
            long oldCount = 0; //to keep updated the old files count for makig single pdf

            #region creatingTempImageLocation
            //Creating Temp image location and first clear all if already there
            string tempLocation = Path.Combine(Path.GetTempPath(), "securepdf");

            if (Directory.Exists(tempLocation))
            {
                try
                {
                    Directory.Delete(tempLocation, true);
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.ToString());
                }
            }

            Directory.CreateDirectory(tempLocation);

            string tempImageLocation = tempLocation;

            #endregion creatingTempImageLocation

            if (convertToSingle == true)
            {
                saveFilePath = saveFilePathForConvertToSingle;
            }

            foreach (string sourcePath in sourceFilesPaths)
            {
                if (!File.Exists(sourcePath))
                {
                    System.Windows.MessageBox.Show("Please select source pdf file first");
                    return;
                }

                if (isBatch == true)
                {
                    MainWindow.currentProcessingFile = "Processing: " + Path.GetFileName(sourcePath);
                }

                if (convertToSingle == false)
                {
                    saveFilePath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileName(sourcePath).Replace(".pdf", "Secured.pdf"));
                }

                #region convertToSecureAndReportProgress
                PDFWrapper pdfWrapper = new PDFWrapper();

                pdfWrapper.LoadPDF(sourcePath);

                //Reporting progress
                worker.ReportProgress(1);

                long pageCount = (long)pdfWrapper.PageCount;

                int  startIndex = 0;
                long endIndex   = pageCount;

                if (convertToSingle == true) //for converting to single pdf
                {
                    startIndex = (int)oldCount;
                    oldCount   = oldCount + pageCount;
                    pageCount  = oldCount;
                }

                float progressUnit   = (float)100.0 / (pageCount * 2);
                float reportProgress = 1;

                #region convertingToImages
                string directoryOfFile = Path.GetDirectoryName(saveFilePath);

                for (var i = startIndex; i <= endIndex; i++)
                {
                    try
                    {
                        //Utility.ConvertPDF2Image(sourcePath, tempImageLocation + "\\", i, i, ImageFormat.Jpeg, Utility.Definition.One, dpi);
                        reportProgress = reportProgress + progressUnit;

                        //Reporting progress
                        worker.ReportProgress((int)reportProgress);
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.ToString());
                    }
                }
                #endregion convertingToImages

                if (convertToSingle == false) //if convertToSingle is false then make individual pdf else make all image and then convert all of them to single pdf
                {
                    convertingImagesToPdf(pageCount, tempImageLocation, reportProgress, progressUnit, worker);
                }


                //Finishing operation and file open dialogue
                worker.ReportProgress(100);
                Thread.Sleep(50);

                //if only one file in the list then show dialogue to open that
                if (isBatch == false)
                {
                    System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Your pdf is now secured, do you want to open it?", "Secured!", System.Windows.MessageBoxButton.YesNo,
                                                                                                      System.Windows.MessageBoxImage.None, MessageBoxResult.None, System.Windows.MessageBoxOptions.DefaultDesktopOnly);
                    if (messageBoxResult == MessageBoxResult.Yes)
                    {
                        Process.Start(saveFilePath);
                    }
                }

                #endregion convertToSecureAndReportProgress
            }


            if (isBatch == true && convertToSingle == true)
            {
                float reportProgress = 1;
                float progressUnit   = (float)100.0 / (oldCount * 2);
                convertingImagesToPdf(oldCount, tempImageLocation, reportProgress, progressUnit, worker);
            }
            else if (isBatch == true)
            {
                System.Windows.MessageBox.Show("Your pdf files are now secured.", "Secured!", System.Windows.MessageBoxButton.OK,
                                               System.Windows.MessageBoxImage.None, MessageBoxResult.None, System.Windows.MessageBoxOptions.DefaultDesktopOnly);
            }
        }
Esempio n. 15
0
            public WrapperUseCountPair(string path)
            {
                Wrapper = new PDFWrapper();
                if (Wrapper.SupportsMuPDF)
                {
                    Wrapper.UseMuPDF = true;
                }

                Wrapper.LoadPDF(stream = new FileStream(Path = path, FileMode.Open));
                Count = 1;
                Disposed = false;
            }
        /// <summary>
        /// Load pdf file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool LoadFile(string fileName)
        {
            bool isrmsProtect = true;

            byte[] license = null;

            try
            {
                //RMS化PDFファイルから、RMSライセンス情報と、暗号化された本文情報を分割する
                //RMS署名情報から、RMSサーバー情報を抽出する
                //RMSサーバーでの認証
                //RMSサーバーからRMSライセンスの取得
                license = SafeFileApiNativeMethods.IpcfGetSerializedLicenseFromFile(fileName);
            }
            catch (Exception ex)
            {
                isrmsProtect = false;
            }

            if (isrmsProtect)
            {
                try
                {
                    //SymmetricKeyCredential symmkey = new SymmetricKeyCredential();
                    //symmkey.AppPrincipalId = "0C5BDABD-CF4D-4FBB-BF4A-DD62BCF7E976";
                    //symmkey.Base64Key = "P@ssw0rd";
                    //symmkey.BposTenantId = "*****@*****.**";

                    SymmetricKeyCredential symmkey = null;

                    //RMSライセンスから、復号鍵の抽出
                    SafeInformationProtectionKeyHandle keyHandle = SafeNativeMethods.IpcGetKey(license, false, false, true, this);
                    //symmkey = (SymmetricKeyCredential)keyHandle;

                    //RMSライセンスから、権利リストの抽出
                    //Collection<UserRights> userRights = new Collection<UserRights>();
                    //userRights = SafeNativeMethods.IpcGetSerializedLicenseUserRightsList(license, keyHandle);

                    bool accessGranted = SafeNativeMethods.IpcAccessCheck(keyHandle, "VIEW");

                    if (accessGranted)
                    {
                        SafeFileApiNativeMethods.IpcfDecryptFile(fileName,
                                                                 SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT,
                                                                 false,
                                                                 false,
                                                                 true,
                                                                 this,
                                                                 symmkey);
                    }

                    //使用権限が正しく設定されていません
                    //ConnectionInfo connectionInfo = SafeNativeMethods.IpcGetSerializedLicenseConnectionInfo(license);
                    //System.Collections.ObjectModel.Collection<TemplateIssuer> templateIssuerList = SafeNativeMethods.IpcGetTemplateIssuerList(connectionInfo, false, false, false, false, this, symmkey);
                    //TemplateIssuer templateIssuer = templateIssuerList[0];
                    //SafeInformationProtectionLicenseHandle licenseHandle = SafeNativeMethods.IpcCreateLicenseFromScratch(templateIssuer);
                    //SafeFileApiNativeMethods.IpcfEncryptFile(fileName, licenseHandle, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, false, false, this, symmkey);

                    //テンプレートは管理者によって作成されていません
                    //TemplateInfo templateInfo = SafeNativeMethods.IpcGetSerializedLicenseDescriptor(license, keyHandle, System.Globalization.CultureInfo.CurrentCulture);
                    //SafeFileApiNativeMethods.IpcfEncryptFile(fileName, templateInfo.TemplateId, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, false, true, this, null);
                }
                catch (InformationProtectionException ex)
                {
                    isrmsProtect = false;
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    isrmsProtect = false;
                }
            }



            try
            {
                pdfDoc.LoadPDF(fileName);

                return(true);
            }
            catch (System.Security.SecurityException sex)
            {
                String password = Interaction.InputBox("Please enter the document password:"******"Document Password", "");
                if (password.Equals(string.Empty))
                {
                    return(false);
                }

                if (pdfDoc != null)
                {
                    pdfDoc.Dispose();
                    pdfDoc = null;
                }
                pdfDoc = new PDFWrapper();
                pdfDoc.UserPassword = password;
                return(LoadFile(fileName));
            }
            catch (Exception ex)
            {
                return(false);
            }
        }