internal static bool PrintImagesToPrinter(PDFLibNet.PDFWrapper pdfDoc) { PrintDialog pd = new PrintDialog(); pd.AllowPrintToFile = false; pd.AllowSomePages = true; pd.PrinterSettings.FromPage = pd.PrinterSettings.MinimumPage = 1; pd.PrinterSettings.ToPage = pd.PrinterSettings.MaximumPage = pdfDoc.PageCount; if (pd.ShowDialog() == DialogResult.OK) { PrintDocument printDocument = new PrintDocument(); printDocument.PrintController = new StandardPrintController(); printDocument.PrinterSettings = pd.PrinterSettings; PrinterUtil printUtil = new PrinterUtil(printDocument, pdfDoc); Cursor.Current = Cursors.WaitCursor; printUtil.printDocument.Print(); bool retVal = printUtil.finishedPrinting; printUtil = null; GC.Collect(); Cursor.Current = Cursors.Default; return(retVal); } else { return(false); } }
private void button1_Click(object sender, EventArgs e) { if (!File.Exists(pdfdoc)) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Portable Document Format (*.pdf)|*.pdf"; if (dlg.ShowDialog() == DialogResult.OK) { pdfdoc = dlg.FileName; } else { return; } } _pdfDoc = new PDFLibNet.PDFWrapper(); _pdfDoc.UseMuPDF = true; try { bool b = _pdfDoc.LoadPDF(pdfdoc); _pdfDoc.CurrentPage = 1; //render button4_Click(sender, e); } catch (Exception ex) { string s = ex.Message; MessageBox.Show(s); System.Environment.Exit(1); } }
public procData(ListView lv, ImageList iml, PDFLibNet.PDFWrapper doc, int page) { pdfDoc = doc; pageNumber = page; listView = lv; imageList = iml; }
private void button1_Click(object sender, EventArgs e) { if (!File.Exists(pdfdoc)) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Portable Document Format (*.pdf)|*.pdf"; if (dlg.ShowDialog() == DialogResult.OK) pdfdoc = dlg.FileName; else return; } _pdfDoc = new PDFLibNet.PDFWrapper(); _pdfDoc.UseMuPDF = true; try { bool b = _pdfDoc.LoadPDF(pdfdoc); _pdfDoc.CurrentPage = 1; //render button4_Click(sender, e); } catch (Exception ex) { string s = ex.Message; MessageBox.Show(s); System.Environment.Exit(1); } }
private void button2_Click(object sender, EventArgs e) { if (_pdfDoc != null) { _pdfDoc.Dispose(); _pdfDoc = null; } }
private PrinterUtil(PrintDocument printDocument, PDFLibNet.PDFWrapper pdfDoc) { this.printDocument = printDocument; this.pdfDoc = pdfDoc; this.endPage = printDocument.PrinterSettings.ToPage; this.currentPage = printDocument.PrinterSettings.FromPage; printDocument.PrintPage += PrintDocument_PrintPage; printDocument.EndPrint += PrintDocument_EndPrint; }
public frmExportJpg(PDFLibNet.PDFWrapper doc, string fileName) { InitializeComponent(); txtFileName.Text = fileName; _doc = doc; udTopage.Maximum = _doc.PageCount; udFromPage.Maximum = _doc.PageCount - 1; udTopage.Value = _doc.PageCount; }
public void LoadImageList(PDFLibNet.PDFWrapper pdfDoc, int pageNumber) { //while (pdfDoc.IsBusy) System.Threading.Thread.Sleep(50); System.ComponentModel.BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(bg_DoWork); bg.ProgressChanged += new ProgressChangedEventHandler(bg_ProgressChanged); bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted); //bg.RunWorkerAsync(new procData(this,_largeImages, pdfDoc,pageNumber)); this.AddImages(new procData(this, _largeImages, pdfDoc, pageNumber)); }
public bool Print(string filename) { //TODO if (filename != null && filename != "" && ImageUtil.IsPDF(filename)) { PDFLibNet.PDFWrapper tmpDoc = new PDFLibNet.PDFWrapper(""); tmpDoc.LoadPDF(filename); return(PrinterUtil.PrintImagesToPrinter(tmpDoc)); } else { return(false); } }
public string ReadPDF(string pdfPath) { PDFLibNet.PDFWrapper wrapper = new PDFLibNet.PDFWrapper(); wrapper.LoadPDF(pdfPath); int i = wrapper.PageCount; string page1Text = string.Empty; for (int j = 1; j <= i; j++) { page1Text += Environment.NewLine + wrapper.Pages[j].Text; } return(page1Text); }
/* ----------------------------------------------------------------- */ /// /// Open /// /// <summary> /// 指定された PDF ファイルを開いて,最初のページを描画する. /// MEMO: パスの記憶場所を検討中.現在は,Parent.Tag を利用 /// している. /// </summary> /// /* ----------------------------------------------------------------- */ public static void Open(Canvas canvas, string path, string password, FitCondition which) { if (canvas == null) { return; } var engine = canvas.Tag as CanvasEngine; if (engine != null) { CanvasPolicy.Close(canvas); } var core = new PDF(); engine = new CanvasEngine(core); canvas.Tag = engine; core.UseMuPDF = true; core.UserPassword = password; core.OwnerPassword = password; if (core.LoadPDF(path)) { core.CurrentPage = 1; if (which == FitCondition.Height) { core.FitToHeight(canvas.Parent.Handle); core.Zoom = core.Zoom - 1; // 暫定 } else if (which == FitCondition.Width) { core.FitToWidth(canvas.Parent.Handle); core.Zoom = core.Zoom - 1; // 暫定 } else { core.Zoom = 100; } canvas.Parent.Text = System.IO.Path.GetFileNameWithoutExtension(path); canvas.Parent.Tag = path; CanvasPolicy.AsyncRender(canvas, true); } }
/* ----------------------------------------------------------------- */ /// ThumbEngine /* ----------------------------------------------------------------- */ public ThumbEngine(PDF core, int width) { core_ = core; width_ = width; var tmp = System.Environment.GetEnvironmentVariable("tmp"); if (tmp == null) { tmp = System.Environment.GetEnvironmentVariable("temp"); } if (tmp == null) { var exec = System.Reflection.Assembly.GetEntryAssembly(); tmp = System.IO.Path.GetDirectoryName(exec.Location); } cached_ = tmp + '\\' + System.IO.Path.GetRandomFileName(); System.IO.Directory.CreateDirectory(cached_); worker_.DoWork -= new DoWorkEventHandler(DoWorkHandler); worker_.DoWork += new DoWorkEventHandler(DoWorkHandler); worker_.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(RunCompletedHandler); worker_.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunCompletedHandler); }
/* ----------------------------------------------------------------- */ /// constructor /* ----------------------------------------------------------------- */ public CanvasEngine(PDF core) { core_ = core; Thumbnail = null; }
public bool Print(string filename) { //TODO if (filename != null && filename != "" && ImageUtil.IsPDF(filename)) { PDFLibNet.PDFWrapper tmpDoc = new PDFLibNet.PDFWrapper(""); tmpDoc.LoadPDF(filename); return PrinterUtil.PrintImagesToPrinter(tmpDoc); } else return false; }
/* ----------------------------------------------------------------- */ /// /// Dispose /// /// <summary> /// TODO: worker を何とかする. /// </summary> /// /* ----------------------------------------------------------------- */ protected virtual void Dispose(bool disposing) { if (!disposed_) { if (disposing) { lock (internal_lock_) { lock (lock_) { queue_.Clear(); } worker_.Dispose(); this.Clear(); lock (core_) { core_ = null; } try { if (cached_ != null && System.IO.Directory.Exists(cached_)) { System.IO.Directory.Delete(cached_, true); } } catch (Exception err) { Utility.ErrorLog(err); } } } } disposed_ = true; }
//------------------------------------------------------------------------- private PDFLibNet.PDFWrapper GetPDFDoc(string fileName) { PDFLibNet.PDFWrapper pdfDoc = new PDFLibNet.PDFWrapper(); pdfDoc.UseMuPDF = true; pdfDoc.LoadPDF(fileName); return pdfDoc; }
/* ----------------------------------------------------------------- */ /// ThumbEngine /* ----------------------------------------------------------------- */ public ThumbEngine(PDF core, int width) { core_ = core; width_ = width; var tmp = System.Environment.GetEnvironmentVariable("tmp"); if (tmp == null) tmp = System.Environment.GetEnvironmentVariable("temp"); if (tmp == null) { var exec = System.Reflection.Assembly.GetEntryAssembly(); tmp = System.IO.Path.GetDirectoryName(exec.Location); } cached_ = tmp + '\\' + System.IO.Path.GetRandomFileName(); System.IO.Directory.CreateDirectory(cached_); worker_.DoWork -= new DoWorkEventHandler(DoWorkHandler); worker_.DoWork += new DoWorkEventHandler(DoWorkHandler); worker_.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(RunCompletedHandler); worker_.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunCompletedHandler); }
private void ConvertPdfToJpg(string movedPath, string targetPath) { string convertPath = string.Empty; try { DateTime st = DateTime.Now; if (File.Exists(movedPath)) { pdfDoc = new PDFLibNet.PDFWrapper(); pdfDoc.ExportJpgFinished += pdfDoc_ExportJpgFinished; pdfDoc.LoadPDF(movedPath); convertPath = targetPath + ".jpg"; mMovedPath = movedPath; mConvertPath = convertPath; mTargetPath = targetPath; pdfDoc.ExportJpg(convertPath, 1, 1, 150, 90, 1); } else { throw new Exception(); } } catch (Exception ex) { pdfDoc.Dispose(); if (File.Exists(movedPath)) File.Delete(movedPath); throw new Exception("ConvertPdfToJpg Convert exception", ex); } }
public void Append(byte[] bytes) { using (var ms = new MemoryStream(bytes)) { switch (LibPDFTools.GetImageFileType(bytes)) { case ImageFileType.PDF: using (var pdfDoc = new PDFLibNet.PDFWrapper("")) { pdfDoc.LoadPDF(ms); for (var i = 1; i <= pdfDoc.PageCount; i++) { pdfDoc.CurrentPage = i; pdfDoc.CurrentX = 0; pdfDoc.CurrentY = 0; pdfDoc.RenderDPI = this.resolution; Bitmap pageBuffer = null; using (var oPictureBox = new PictureBox()) { pdfDoc.RenderPage(oPictureBox.Handle); pageBuffer = new Bitmap(pdfDoc.PageWidth, pdfDoc.PageHeight); pdfDoc.ClientBounds = new System.Drawing.Rectangle(0, 0, pdfDoc.PageWidth, pdfDoc.PageHeight); using (var g = Graphics.FromImage(pageBuffer)) { var hdc = g.GetHdc(); pdfDoc.DrawPageHDC(hdc); g.ReleaseHdc(); } } SaveAddTiffPage(pageBuffer); pageBuffer.Dispose(); currPageNum++; } } break; case ImageFileType.TIFF: { using (var image = System.Drawing.Image.FromStream(ms)) { var fd = new System.Drawing.Imaging.FrameDimension(image.FrameDimensionsList[0]); int numberOfPages = image.GetFrameCount(fd); for (int pageNum = 0; pageNum < numberOfPages; pageNum++) { image.SelectActiveFrame(fd, pageNum); if (currPageNum == 0) { backbuffer = (System.Drawing.Image)image.Clone(); backbuffer.Save(outStream, codec, encoderParameters_MultiFrame); } else { backbuffer.SaveAdd(image, encoderParameters_FrameDimensionPage); } currPageNum++; } } } break; default: { var pageBuffer = System.Drawing.Image.FromStream(ms); SaveAddTiffPage(pageBuffer); } currPageNum++; break; } } }
/* ----------------------------------------------------------------- */ /// Dispose /* ----------------------------------------------------------------- */ protected virtual void Dispose(bool disposing) { lock (lock_) { if (!disposed_) { if (disposing) { urls_.Clear(); if (core_ != null) core_ = null; } } disposed_ = true; } }
/* ----------------------------------------------------------------- */ /// /// Open /// /// <summary> /// 指定された PDF ファイルを開いて,最初のページを描画する. /// MEMO: パスの記憶場所を検討中.現在は,Parent.Tag を利用 /// している. /// </summary> /// /* ----------------------------------------------------------------- */ public static void Open(Canvas canvas, string path, string password, FitCondition which) { if (canvas == null) return; var engine = canvas.Tag as CanvasEngine; if (engine != null) CanvasPolicy.Close(canvas); var core = new PDF(); engine = new CanvasEngine(core); canvas.Tag = engine; core.UseMuPDF = true; core.UserPassword = password; core.OwnerPassword = password; if (core.LoadPDF(path)) { core.CurrentPage = 1; if (which == FitCondition.Height) { core.FitToHeight(canvas.Parent.Handle); core.Zoom = core.Zoom - 1; // 暫定 } else if (which == FitCondition.Width) { core.FitToWidth(canvas.Parent.Handle); core.Zoom = core.Zoom - 1; // 暫定 } else core.Zoom = 100; canvas.Parent.Text = System.IO.Path.GetFileNameWithoutExtension(path); canvas.Parent.Tag = path; CanvasPolicy.AsyncRender(canvas, true); } }
public SigmaResultType AddDrawingImage(string sourcePath, string targetPath) { SigmaResultType result = new SigmaResultType(); TransactionScope scope = null; TypeUserInfo userinfo = AuthMgr.GetUserInfo(); //PDFLibNet.PDFWrapper pdfDoc; PDFLibNet.PDFWrapper pdfDoc = new PDFLibNet.PDFWrapper(); //// target directory 는 쿠키 값 확인하여 추가 경로를 생성해야 된다. //// 추가 경로 --> [company]/[project id]/[document type]/[document name(id)]/[document revision] //string targetChildPath = "Company\\" + "Project\\" + "Drawing\\"; string targetChildPath = userinfo.CompanyName + "\\" + userinfo.CurrentProjectId + "\\" + "Drawing\\"; targetPath = targetPath + targetChildPath; // Source Path에서 읽고 확인 후 정상이면 Target Path로 이동 string[] filePaths = Directory.GetFiles(sourcePath); // Get connection string string connStr = ConnStrHelper.getDbConnString(); // * [1] Image file upload - multiple files foreach (string path in filePaths) { string convertfilepath = string.Empty; string Importedfilename = Path.GetFileNameWithoutExtension(path); FileInfo fileinfo = new FileInfo(path); long fileSize = fileinfo.Length; // byte string fileExtention = Path.GetExtension(path); string fileType = "FILE_TYPE_DRAWING"; string CreateBy = userinfo.SigmaUserId; int fileStroeId; int fileId; string fileCategory = "FILE_CATEGORY_DRAWING"; if (fileExtention == ".pdf" || fileExtention == ".PDF") { // pdf --> jpg 로 변경해서 등록 pdfDoc.LoadPDF(path); //pdfDoc.RenderPage(); convertfilepath = targetPath + Importedfilename + ".jpg"; //pdfDoc.ExportJpg(@"c:\temp\page_pdf%d.jpg", 1, 1, 150, 90); //*** waitpoc --> 동기화, 비동기화 --> 기다릴 거냐? pdfDoc.ExportJpg(convertfilepath, 1, 1, 150, 90, 1); //** Dispose 시점을 늦춰 본다.. 아래 foreach end 시점 -- Object X foreach 밖으로 사용 후에 처리 할 것 //pdfDoc.Dispose() } else if (fileExtention == ".xls" || fileExtention == ".xlsx") continue; //--------------------------------------------------------------------------- SqlParameter[] fileStoreParm = new SqlParameter[] { new SqlParameter("@FileStoreID", SqlDbType.Int, 10), // sp에서 output 설정했을 경우 new SqlParameter("@Title", Importedfilename), new SqlParameter("@Description", Importedfilename), new SqlParameter("@Category", fileCategory), new SqlParameter("@TypeCode", fileType), new SqlParameter("@CreatedBy", CreateBy), new SqlParameter("RETURN_VALUE",SqlDbType.Int) // sp에서 return 값을 설정했을경우 사용 }; fileStoreParm[0].Direction = ParameterDirection.Output; fileStoreParm[6].Direction = ParameterDirection.ReturnValue; // 하나의 TransctionScope으로.. using (scope = new TransactionScope(TransactionScopeOption.Required)) { result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddFileStoreDrawing", fileStoreParm); fileStroeId = (int)fileStoreParm[0].Value; int AffectedRow = (int)fileStoreParm[6].Value; string targetFilePath = targetChildPath + Importedfilename + ".jpg"; // Compose parameters SqlParameter[] uploadfileParm = new SqlParameter[] { new SqlParameter("@UploadedFileInfoId", SqlDbType.Int, 10), // sp에서 output 설정했을 경우 new SqlParameter("@FileStoreID", fileStroeId), new SqlParameter("@Name", Importedfilename), new SqlParameter("@Size", fileSize), //new SqlParameter("@Path", path), new SqlParameter("@Path", targetFilePath), new SqlParameter("@FileExtension", fileExtention), new SqlParameter("@Revision", "None"), new SqlParameter("@FileType", fileType), new SqlParameter("@CreatedBy", CreateBy), new SqlParameter("RETURN_VALUE",SqlDbType.Int) // sp에서 return 값을 설정했을경우 사용 }; uploadfileParm[0].Direction = ParameterDirection.Output; uploadfileParm[9].Direction = ParameterDirection.ReturnValue; result.AffectedRow = SqlHelper.ExecuteNonQuery(connStr, CommandType.StoredProcedure, "usp_AddUploadedFileInfoDrawing", uploadfileParm); fileId = (int)uploadfileParm[0].Value; int uploadAffectedRow = (int)uploadfileParm[9].Value; scope.Complete(); } } pdfDoc.Dispose(); pdfDoc = null; // * [2] To Copy all the files (in source directory -> to target directory) //MemoryStream destination = new MemoryStream(); if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } if (System.IO.Directory.Exists(sourcePath)) { string[] sourcefilePaths = Directory.GetFiles(sourcePath); foreach (string sourceFile in sourcefilePaths) { string sourcefilename = Path.GetFileNameWithoutExtension(sourceFile); string fileExtention = Path.GetExtension(sourceFile); //string sourceFile = System.IO.Path.Combine(sourcePath, sourcefilename); string destFile = System.IO.Path.Combine(targetPath, sourcefilename + fileExtention); try { // *** converted jpg File string strSavePath = targetPath + sourcefilename + ".jpg"; // Thumbnail 비율 적용 - 원본 이미지의 가로:세율 비율 확인 - 축소 길이 - 가로 고정 - 200) System.IO.Stream imgstream = File.Open(strSavePath, FileMode.Open); System.Drawing.Image sourceImage = System.Drawing.Image.FromStream(imgstream); float orgheight = sourceImage.PhysicalDimension.Height; float orgwidth = sourceImage.PhysicalDimension.Width; int newwidth = 200; float newheight = orgheight / orgwidth * newwidth; System.Drawing.Image thumbnailImage = sourceImage.GetThumbnailImage(newwidth, (int)newheight, null, IntPtr.Zero); thumbnailImage.Save(targetPath + sourcefilename + ".thumbnail" + ".jpg"); imgstream.Dispose(); // pdf file copy to DocumentFolderRoot System.IO.File.Copy(sourceFile, destFile, true); } catch (System.IO.IOException copye) { //Console.WriteLine(copye.Message); result.ErrorMessage = copye.Message + " copy error"; result.IsSuccessful = false; return result; } } } else { //Console.WriteLine("Source path does not exist!"); result.ErrorMessage = "Source path : " + sourcePath + " does not exist!"; result.IsSuccessful = false; return result; } // * [3] Delete source files - optional try { string[] sourcefilePaths = Directory.GetFiles(sourcePath); foreach (string sourceFile in sourcefilePaths) { System.IO.File.Delete(sourceFile); } } catch (System.IO.IOException dele) { //Console.WriteLine(dele.Message); result.ErrorMessage = dele.Message + " delete error"; result.IsSuccessful = false; return result; } result.IsSuccessful = true; return result; }
void OpenFile(string path) { var doc = new PDFLibNet.PDFWrapper(); doc.UseMuPDF = true; doc.LoadPDF(path); m_path = path; m_doc = doc; LoadImages(); }