Beispiel #1
0
 private void tsbOpen_Click(object sender, EventArgs e)
 {
     this._pdfDoc = (PDFWrapper)null;
     try
     {
         OpenFileDialog openFileDialog = new OpenFileDialog();
         openFileDialog.Filter = "Portable Document Format (*.pdf)|*.pdf";
         if (openFileDialog.ShowDialog() != DialogResult.OK)
         {
             return;
         }
         if (this._pdfDoc == null)
         {
             this._pdfDoc = new PDFWrapper();
             this._pdfDoc.PDFLoadCompeted += new PDFLoadCompletedHandler(this._pdfDoc_PDFLoadCompeted);
             this._pdfDoc.PDFLoadBegin    += new PDFLoadBeginHandler(this._pdfDoc_PDFLoadBegin);
         }
         this.pageViewControl1.Visible = false;
         if (!this.LoadFile(openFileDialog.FileName))
         {
             return;
         }
         this._pdfDoc.CurrentPage = 1;
         this.Text = "Powered by xPDF: " + this._pdfDoc.Author + " - " + this._pdfDoc.Title;
         this.FillTree();
         this.FitWidth();
         this.Render();
         this.pageViewControl1.PageSize = new Size(this._pdfDoc.PageWidth, this._pdfDoc.PageHeight);
         this.pageViewControl1.Visible  = true;
     }
     catch (Exception ex)
     {
         int num = (int)MessageBox.Show(ex.ToString());
     }
 }
Beispiel #2
0
        public static Image RenderPage(PDFWrapper doc, int page)
        {
            doc.CurrentPage = page + 1;
            doc.CurrentX    = 0;
            doc.CurrentY    = 0;

            doc.RenderPage(IntPtr.Zero);

            // create an image to draw the page into
            var buffer = new Bitmap(doc.PageWidth, doc.PageHeight);

            doc.ClientBounds = new Rectangle(0, 0, doc.PageWidth, doc.PageHeight);
            using (var g = Graphics.FromImage(buffer))
            {
                var hdc = g.GetHdc();
                try
                {
                    doc.DrawPageHDC(hdc);
                }
                finally
                {
                    g.ReleaseHdc();
                }
            }
            return(buffer);
        }
Beispiel #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();
        }
Beispiel #4
0
        private bool LoadFile(string filename, PDFWrapper pdfDoc)
        {
            //try
            //{
            //    if (this.fs != null)
            //    {
            //        this.fs.Close();
            //        this.fs = (FileStream)null;
            //    }
            //    bool flag = pdfDoc.LoadPDF(filename);
            //    //this.tsbUseMuPDF.Checked = pdfDoc.UseMuPDF;
            //    return flag;
            //}
            //catch (SecurityException ex)
            //{
            //    //
            //    // Formulario para Socitar el Password del PDF
            //    //

            //    //frmPassword frmPassword = new frmPassword();
            //    //if (frmPassword.ShowDialog() == DialogResult.OK)
            //    //{
            //    //    if (!frmPassword.UserPassword.Equals(string.Empty))
            //    //        pdfDoc.UserPassword = frmPassword.UserPassword;
            //    //    if (!frmPassword.OwnerPassword.Equals(string.Empty))
            //    //        pdfDoc.OwnerPassword = frmPassword.OwnerPassword;
            //    //    return this.LoadFile(filename, pdfDoc);
            //    //}
            //    int num = (int)MessageBox.Show("El archivo esta encriptado", this.Text);
            //    return false;
            //}
            return(false);
        }
Beispiel #5
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();
            }
        }
Beispiel #6
0
 private void frmPDFViewer_FormClosed(object sender, FormClosedEventArgs e)
 {
     if (_pdfDoc != null)
     {
         _pdfDoc.Dispose();
         _pdfDoc = null;
     }
     GC.Collect();
 }
Beispiel #7
0
 private void toolStripButton5_Click(object sender, EventArgs e)
 {
     listView2.Items.Clear();
     if (_pdfDoc != null)
     {
         _pdfDoc.Dispose();
         _pdfDoc = null;
     }
     Close();
 }
Beispiel #8
0
 public bool UnloadPdf()
 {
     if (mypdfDoc != null)
     {
         //MessageBox.Show("UnloadPDF");
         mypdfDoc.Dispose();
         mypdfDoc = null;
         return(true);
     }
     return(false);
 }
Beispiel #9
0
        static void Main(string[] args)
        {
            string inputPPT = @"e:/test.pdf";
            string savaFile = @"E:/imgage/";

            CommonPPT.Test();

            PDFWrapper pdfWrapper = new PDFWrapper();

            CommonPPT.ConvertPDF2Image(inputPPT, savaFile, "testimgage", 1, 4, ImageFormat.Jpeg, CommonPPT.Definition.One);

            Console.ReadKey();
        }
        private void CloseFile()
        {
            if (this._pdfDoc == null)
            {
                return;
            }

            this._pdfDoc.PDFLoadCompeted -= new PDFLoadCompletedHandler(this._pdfDoc_PDFLoadCompeted);
            this._pdfDoc.PDFLoadBegin    -= new PDFLoadBeginHandler(this._pdfDoc_PDFLoadBegin);

            this._pdfDoc.Dispose();
            this._pdfDoc = null;

            ПослеВыгрузкиФайла?.Invoke();
        }
Beispiel #11
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;
                }
            }
        }
Beispiel #12
0
        protected override void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                if (_document != null)
                {
                    _document.Dispose();
                    _document = null;
                }

                if (_dummyControl != null)
                {
                    _dummyControl.Dispose();
                    _dummyControl = null;
                }

                _disposed = true;
            }
        }
Beispiel #13
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="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;
     }
 }
Beispiel #15
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());
            }
        }
 private bool LoadFile(string filename)
 {
     try
     {
         this.pageViewControl1.Visible = false;
         if (this._pdfDoc == null)
         {
             this._pdfDoc = new PDFWrapper();
             this._pdfDoc.PDFLoadCompeted += new PDFLoadCompletedHandler(this._pdfDoc_PDFLoadCompeted);
             this._pdfDoc.PDFLoadBegin    += new PDFLoadBeginHandler(this._pdfDoc_PDFLoadBegin);
         }
         return(this._pdfDoc.LoadPDF(filename));
     }
     catch (SecurityException ex)
     {
         frmPassword frmPassword = new frmPassword();
         if (frmPassword.ShowDialog() == DialogResult.OK)
         {
             if (!frmPassword.UserPassword.Equals(string.Empty))
             {
                 this._pdfDoc.UserPassword = frmPassword.UserPassword;
             }
             if (!frmPassword.OwnerPassword.Equals(string.Empty))
             {
                 this._pdfDoc.OwnerPassword = frmPassword.OwnerPassword;
             }
             return(this.LoadFile(filename));
         }
         int num = (int)MessageBox.Show("File encrypted", this.Text);
         return(false);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString());
         return(false);
     }
     finally
     {
     }
 }
Beispiel #17
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);
        }
        /// <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();
        }
Beispiel #19
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());
            }
        }
        private void tsbOpen_Click(object sender, EventArgs e)
        {
            this._pdfDoc = (PDFWrapper)null;
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Portable Document Format (*.pdf)|*.pdf";
                if (openFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                this.pageViewControl1.Visible = false;

                if (!this.LoadFile(openFileDialog.FileName))
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                int num = (int)MessageBox.Show(ex.ToString());
            }
        }
        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;
                }
            }
                            
        }
Beispiel #22
0
        protected override void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                if (_document != null)
                {
                    _document.Dispose();
                    _document = null;
                }

                if (_dummyControl != null)
                {
                    _dummyControl.Dispose();
                    _dummyControl = null;
                }

                _disposed = true;
            }
        }
 public loadPagesParam(PDFWrapper pdf, ListView lv)
 {
     pdfDoc = pdf;
     listView = lv;
 }
        private void tsbOpen_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "Portable Document Format (*.pdf)|*.pdf";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    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;
                    //}
                    //xPDFParams.ErrorQuiet =true;
                    //xPDFParams.ErrorFile = "C:\\stderr.log";
                    //}
                    int ts = Environment.TickCount;
                    using (StatusBusy sb = new StatusBusy(Resources.UIStrings.StatusLoadingFile))
                    {
                        if (LoadFile(dlg.FileName, _pdfDoc))
                        {
                            Text = string.Format(Resources.UIStrings.StatusFormCaption, _pdfDoc.Author, _pdfDoc.Title);
                            FillTree();
                            _pdfDoc.CurrentPage = 1;
                            UpdateText();

                            _pdfDoc.FitToWidth(pageViewControl1.Handle);
                            _pdfDoc.RenderPage(pageViewControl1.Handle);

                            Render();

                            PDFPage pg = _pdfDoc.Pages[1];
                            listView2.TileSize = new Size(134, (int)(128 * pg.Height / pg.Width) + 10);
                            listView2.BeginUpdate();
                            listView2.Clear();
                            for (int i = 0; i < _pdfDoc.PageCount; ++i)
                                listView2.Items.Add((i + 1).ToString());
                            listView2.EndUpdate();

                            //pg.LoadThumbnail(128, (int)(128 * pg.Height / pg.Width));
                        }
                    }
                }
            }
            catch (System.IO.IOException ex)
            {
                MessageBox.Show(ex.Message, "IOException");
            }
            catch (System.Security.SecurityException ex)
            {
                MessageBox.Show(ex.Message, "SecurityException");
            }
            catch (System.IO.InvalidDataException ex)
            {
                MessageBox.Show(ex.Message, "InvalidDataException");
            }
        }
 private void toolStripButton5_Click(object sender, EventArgs e)
 {
     listView2.Items.Clear();
     if (_pdfDoc != null)
     {
         _pdfDoc.Dispose();
         _pdfDoc = null;
     }
     Close();
 }
 private void frmPDFViewer_FormClosed(object sender, FormClosedEventArgs e)
 {
     if (_pdfDoc != null)
     {
         _pdfDoc.Dispose();
         _pdfDoc = null;
     }
     GC.Collect();
 }
        /// <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);
            }
        }
        /// <summary>
        /// Form initialization
        /// </summary>
        /// <param name="fileName">fileName</param>
        private void FormInitial(string fileName)
        {
            rmsUserpEncrypt = true;

            if (outPutStream != null)
            {
                outPutStream.Close();
                outPutStream.Dispose();
            }

            if (!tempFile.Equals(string.Empty))
            {
                if (File.Exists(tempFile + ".tmp"))
                {
                    WipeFile(tempFile + ".tmp", 1);
                }
                tempFile = string.Empty;
            }

            if (pdfDoc != null)
            {
                pdfDoc.Dispose();
                pdfDoc = null;
            }
            pdfDoc = new PDFWrapper();

            if (!LoadFileByStream(fileName))
            {
                return;
            }
            //set zoomRate
            if (zoomRate.Count == 0)
            {
                zoomRate.Add(-3, 0.25);
                zoomRate.Add(-2, 0.5);
                zoomRate.Add(-1, 0.75);
                zoomRate.Add(0, 1);
                zoomRate.Add(1, 1.25);
                zoomRate.Add(2, 1.5);
                zoomRate.Add(3, 2);
                zoomRate.Add(4, 4);
            }

            foreach (string item in ddlZoom.Items)
            {
                if (item.Equals((zoomRate[currentZoom] * 100).ToString() + "%"))
                {
                    ddlZoom.SelectedIndex = currentZoom - (-3);
                }
            }

            currentPage        = pdfDoc.CurrentPage;
            pageCount          = pdfDoc.PageCount;
            tslblPageAll.Text  = "/" + pageCount.ToString();
            tstbPageIndex.Text = currentPage.ToString();

            SetPictureBoxImage();

            this.WindowState = FormWindowState.Maximized;
            this.pnlForm.Focus();
        }
        /// <summary>
        /// Load pdf file by stream
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool LoadFileByStream(string fileName)
        {
            bool   isrmsProtect = true;
            Stream stream       = null;

            byte[] license         = null;
            string rmsUserPassword = string.Empty;


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

            if (isrmsProtect && rmsUserpEncrypt)
            {
                try
                {
                    rmsUserPassword = GenerateRandom(32);

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

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

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

                    //本文情報を復号鍵で、復号
                    tempFile = GenerateRandom(10);

                    //一時フォルダ作成 add kondo
                    System.IO.Directory.CreateDirectory(Path.GetTempPath() + @"PDFViewer\");

                    tempFile = Path.GetTempPath() + @"PDFViewer\" + tempFile;

                    Stream outPutRmsStream = new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    stream = new FileStream(fileName, FileMode.Open);
                    if (accessGranted)
                    {
                        SafeFileApiNativeMethods.IpcfDecryptFileStream(stream, fileName,
                                                                       SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, false,
                                                                       false, false, this, ref outPutRmsStream);
                    }

                    outPutRmsStream.Close();
                    outPutRmsStream.Dispose();

                    PdfReader reader = new PdfReader(tempFile);
                    outPutStream = new FileStream(tempFile + ".tmp", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
                    PdfEncryptor.Encrypt(reader, outPutStream, false, rmsUserPassword, "", 0);

                    rmsUserpEncrypt = false;
                    reader.Close();
                    reader.Dispose();
                    File.Delete(tempFile);
                }
                catch (InformationProtectionException ex)
                {
                    //DirectoryDelete MSIPC
                    DeleteDirectorySelect(true);

                    isrmsProtect = false;
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    isrmsProtect = false;
                }
            }


            try
            {
                if (isrmsProtect)
                {
                    pdfDoc.LoadPDF(tempFile + ".tmp");
                }
                else
                {
                    pdfDoc.LoadPDF(fileName);
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                return(true);
            }
            catch (System.Security.SecurityException sex)
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }

                if (pdfDoc != null)
                {
                    pdfDoc.Dispose();
                    pdfDoc = null;
                }
                pdfDoc = new PDFWrapper();

                if (!rmsUserpEncrypt)
                {
                    pdfDoc.UserPassword = rmsUserPassword;
                }
                else
                {
                    String password = Interaction.InputBox("Please enter the document password:"******"Document Password", "");
                    if (password.Equals(string.Empty))
                    {
                        return(false);
                    }
                    pdfDoc.UserPassword = password;
                }

                return(LoadFileByStream(fileName));
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                return(false);
            }
        }
Beispiel #30
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;
            }
Beispiel #31
0
        private void tsbOpen_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "Portable Document Format (*.pdf)|*.pdf";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    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);
                    //}
                    //xPDFParams.ErrorQuiet =true;
                    //xPDFParams.ErrorFile = "C:\\stderr.log";
                    //}
                    int ts = Environment.TickCount;
                    using (StatusBusy sb = new StatusBusy(Resources.UIStrings.StatusLoadingFile))
                    {
                        if (LoadFile(dlg.FileName, _pdfDoc))
                        {
                            Text = string.Format(Resources.UIStrings.StatusFormCaption, _pdfDoc.Author, _pdfDoc.Title);
                            FillTree();
                            _pdfDoc.CurrentPage = 1;
                            UpdateText();

                            _pdfDoc.FitToWidth(pageViewControl1.Handle);
                            _pdfDoc.RenderPage(pageViewControl1.Handle);

                            Render();

                            PDFPage pg = _pdfDoc.Pages[1];
                            listView2.TileSize = new Size(134, (int)(128 * pg.Height / pg.Width) + 10);
                            listView2.BeginUpdate();
                            listView2.Clear();
                            for (int i = 0; i < _pdfDoc.PageCount; ++i)
                            {
                                listView2.Items.Add((i + 1).ToString());
                            }
                            listView2.EndUpdate();

                            //pg.LoadThumbnail(128, (int)(128 * pg.Height / pg.Width));
                        }
                    }
                }
            }
            catch (System.IO.IOException ex)
            {
                MessageBox.Show(ex.Message, "IOException");
            }
            catch (System.Security.SecurityException ex)
            {
                MessageBox.Show(ex.Message, "SecurityException");
            }
            catch (System.IO.InvalidDataException ex)
            {
                MessageBox.Show(ex.Message, "InvalidDataException");
            }
        }
Beispiel #32
0
 public loadPagesParam(PDFWrapper pdf, ListView lv)
 {
     pdfDoc   = pdf;
     listView = lv;
 }
Beispiel #33
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);
            }
        }