1) 프로젝트에 OfficeToPDF.cs 클래스를 추가한다.
먼저 프린트의 상태를 조회하는 함수를 만들어 보겠습니다 .
프로젝트 참조에 System.Management 를 추가하고, using System.Management 을 추가합니다.
그리고 아래의 코드를 클래스에 추가합니다.
/// <summary>/// 프린터 상태 조회/// </summary>/// <param name="result">결과text</param>/// <returns>true:사용가능 false:사용불가능</returns>public static bool PrintStatus(out string result){ result = string.Empty; ManagementScope scope = new ManagementScope(@"\root\cimv2"); scope.Connect(); ManagementObjectSearcher searcher = new ManagementObjectSearcher ("SELECT * FROM Win32_Printer"); string printName = ""; foreach (ManagementObject printer in searcher.Get()) { printName = printer["Name"].ToString().ToLower(); if (printName.Equals(@"pdfcreator")) { if (printer["WorkOffline"].ToString().ToLower().Equals("true")) { result = "프린터가 사용 가능한 상태가 아닙니다."; return false; } else { result = "프린터가 존재하며 사용 가능한 상태입니다."; return true; } } } result = "PDFCreator 프린터가 존재하지 않습니다."; return false;}
폼에 등록했던 Shown이벤트에 아래 코드를 추가합니다.
// 프린터 상태를 조회하여 상태에 따라 버튼을 // 활성화 한다 .string result = string.Empty;btnConvert.Enabled = OfficeToPDF.PrintStatus(out result);lblInfomation.Text = result;
그럼 빌드한 후 실행해 봅니다.
위와 같이 되면 여기까지 정상적으로 된겁니다. 프린트가 없다고 나온다면 PDFCreator까실때 다른 이름을 주셨거나, 아님 활성화가 안되어 있거나 한 경우이니 PDFCreator를 다시 깔아 보면 해결될껍니다.
2)프로젝트에 PDFOptions.cs 클래스를 추가하고 , 아래와 같이 코딩합니다.
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace PDFConverter{ public class PDFOptions { string _SourceFileName; /// <summary> /// 소스 파일명 /// </summary> public string SourceFileName { get { return _SourceFileName; } set { _SourceFileName = value; } } int _UseAutosave = 1; /// <summary> /// 자동저장여부 /// 0:아니오 1:예 /// </summary> public int UseAutosave { get { return _UseAutosave; } set { _UseAutosave = value; } } int _UseAutosaveDirectory = 1; /// <summary> /// 자동저장 디렉토리 사용여부 /// 0:아니오 1:예 /// </summary> public int UseAutosaveDirectory { get { return _UseAutosaveDirectory; } set { _UseAutosaveDirectory = value; } } string _AutosaveDirectory = @"C:\temp\"; /// <summary> /// 자동저장 디렉토리 기본값은 C:\temp\ /// </summary> public string AutosaveDirectory { get { return _AutosaveDirectory; } set { _AutosaveDirectory = value; } } string _AutosaveFilename; /// <summary> /// 저장파일명 /// </summary> public string AutosaveFilename { get { return _AutosaveFilename; } set { _AutosaveFilename = value; } } int _AutosaveFormat = 0; /// <summary> /// 저장 포멧 /// 0:pdf /// </summary> public int AutosaveFormat { get { return _AutosaveFormat; } set { _AutosaveFormat = value; } } int _PDFCompressionTextCompression = 1; /// <summary> /// 텍스트 압축여부 /// 0:아니오 1:예 /// </summary> public int PDFCompressionTextCompression { get { return _PDFCompressionTextCompression; } set { _PDFCompressionTextCompression = value; } } int _PDFGeneralResolution = 300; /// <summary> /// PDF 해상도 /// 기본값 300 /// </summary> public int PDFGeneralResolution { get { return _PDFGeneralResolution; } set { _PDFGeneralResolution = value; } } }}
3)프로젝트에 PDFResult.cs 클래스를 추가하고 , 아래와 같이 코딩합니다.
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace PDFConverter{ public class PDFResult { private bool _success; /// <summary> /// 변환 성공여부 /// </summary> public bool Success { get { return _success; } set { _success = value; } } private string _resultMessage; /// <summary> /// 변환결과 메시지 /// </summary> public string ResultMessage { get { return _resultMessage; } set { _resultMessage = value; } } private string _outputFileName; /// <summary> /// 출력 파일명 /// </summary> public string OutputFileName { get { return _outputFileName; } set { _outputFileName = value; } } }}
4) OfficeToPDF에 PDFCreator 변수 선언 및 초기화 함수 생성
private clsPDFCreator pdf;
/// <summary>/// 컨버터 초기화/// </summary>/// <param name="opt">컨버팅 옵션</param>/// <returns></returns>private PDFResult InitializeCreator(PDFOptions opt){ PDFResult result = new PDFResult(); pdf = new clsPDFCreator(); if (pdf.cStart("/NoProcessingAtStartup", true) == false) { result.Success = false; result.ResultMessage = "프린터 초기화에 실패 했습니다."; return result; } pdf.cPrinterStop = true; pdf.cClearCache(); pdf.set_cOption("UseAutosave", opt.UseAutosave); pdf.set_cOption("UseAutosaveDirectory", opt.UseAutosaveDirectory); pdf.set_cOption("AutosaveDirectory", opt.AutosaveDirectory); pdf.set_cOption("AutosaveFilename", opt.AutosaveFilename); pdf.set_cOption("AutosaveFormat", opt.AutosaveFormat); pdf.set_cOption("PDFCompressionTextCompression", opt.PDFCompressionTextCompression); pdf.set_cOption("PDFGeneralResolution", opt.PDFGeneralResolution); pdf.cPrinterStop = false; pdf.cPrinterStop = true; result.Success = true; return result;}
5) OfficeToPDF 에 엑셀 변환함수 생성
/// <summary>/// 엑셀 컨버팅/// </summary>/// <param name="opt">컨버팅 옵션</param>/// <returns></returns>private PDFResult ExcelToPDF(PDFOptions opt){ PDFResult result = new PDFResult(); #region 엑셀파일 변환 Excel.Application excel = new Excel.Application(); try { // 엑셀파일 열기 Excel.Workbook wb = excel.Application.Workbooks.Open(opt.SourceFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // 파일 프린트 wb.Worksheets.PrintOut(Type.Missing, Type.Missing, 1, false, "PDFCreator", false, true, Type.Missing); #region pdf 변환 // 프린터 큐에 job이 생성될때까지 기다린다. while (pdf.cCountOfPrintjobs != 1) ; // 인쇄시작 pdf.cPrinterStop = false; // 인쇄가 완료될때 까지 기다린다. while (pdf.cCountOfPrintjobs != 0) ; #endregion #region 문서 닫기 및 PdfCreator 닫기 pdf.cPrinterStop = true; object doNotSaveChanges = false; object missing = Type.Missing; // 엑셀 종료 wb.Close(doNotSaveChanges, missing, missing); excel.Quit(); // PDFCreator 종료 pdf.cClose(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pdf); GC.Collect(); #endregion result.Success = true; result.OutputFileName = opt.AutosaveDirectory + opt.AutosaveFilename; result.ResultMessage = opt.AutosaveFilename + " 으로 변환이 성공 하였습니다"; } catch { result.Success = false; result.ResultMessage = pdf.cError.Description; } #endregion return result;}
6) OfficeToPDF 에 워드 변환함수 생성
/// <summary>/// 워드 컨버팅/// </summary>/// <param name="opt">컨버팅 옵션</param>/// <returns></returns>private PDFResult WordToPDF(PDFOptions opt){ PDFResult result = new PDFResult(); #region 워드파일 인쇄 Word.Application word = new Microsoft.Office.Interop.Word.Application(); try { #region 문서 오픈 object readOnly = true; object fileName = opt.SourceFileName; object missing = Type.Missing; string defaultPrinter = word.Application.ActivePrinter; word.Application.ActivePrinter = "PDFCreator"; Word.Document doc = word.Application.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); #endregion #region 문서 인쇄 Object false_object = false; Object missingValue = Type.Missing; Object background = true; Object append = true; Object range = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument; Object outputFileName = Type.Missing; Object from = Type.Missing; Object to = Type.Missing; Object item = Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent; Object copies = 1; Object pages = Type.Missing; Object pageType = Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages; Object printToFile = false; Object collate = Type.Missing; Object fileNames = Type.Missing; Object activePrinterMacGX = Type.Missing; Object manualDuplexPrint = Type.Missing; Object printZoomColumn = Type.Missing; Object printZoomRow = Type.Missing; Object printZoomPaperWidth = Type.Missing; Object printZoomPaperHeight = Type.Missing; word.Application.PrintOut(ref background, ref append, ref range, ref outputFileName, ref from, ref to, ref item, ref copies, ref pages, ref pageType, ref printToFile, ref collate, ref fileNames, ref activePrinterMacGX, ref manualDuplexPrint, ref printZoomColumn, ref printZoomRow, ref printZoomPaperWidth, ref printZoomPaperHeight); #endregion #region pdf 변환 // 프린터 큐에 job이 생성될때까지 기다린다. while (pdf.cCountOfPrintjobs != 1) ; // 인쇄시작 pdf.cPrinterStop = false; // 인쇄가 완료될때 까지 기다린다. while (pdf.cCountOfPrintjobs != 0) ; // 모든 워드 문서를 닫는다. foreach (Word.Document dd in word.Application.Documents) { dd.Close(ref false_object, ref missingValue, ref missingValue); } #endregion #region 문서 닫기 및 PdfCreator 닫기 pdf.cPrinterStop = true; object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; // 워드 종료 word.Application.ActivePrinter = defaultPrinter; word.Application.Quit(ref doNotSaveChanges, ref missing, ref missing); // 컨버터 종료 pdf.cClose(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pdf); GC.Collect(); #endregion result.Success = true; result.OutputFileName = opt.AutosaveDirectory + opt.AutosaveFilename; result.ResultMessage = opt.AutosaveFilename + " 으로 변환이 성공 하였습니다"; } catch { result.Success = false; result.ResultMessage = pdf.cError.Description; } #endregion return result;}
7) OfficeToPDF 에 파워포인트 변환함수 생성
/// <summary>/// 파워포인트 컨버팅/// </summary>/// <param name="opt">컨버팅 옵션</param>/// <returns></returns>private PDFResult PowerPointToPDF(PDFOptions opt){ PDFResult result = new PDFResult(); #region 파워포인트 변환 PowerPoint.Application power = new Microsoft.Office.Interop.PowerPoint.Application(); try { string defaultPrinter = power.ActivePrinter; PowerPoint.Presentation pres = power.Presentations.Open(opt.SourceFileName, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse); pres.PrintOptions.ActivePrinter = "PDFCreator"; pres.PrintOptions.PrintInBackground = Microsoft.Office.Core.MsoTriState.msoCTrue; pres.PrintOut(1, pres.Slides.Count, string.Empty, 1, Microsoft.Office.Core.MsoTriState.msoFalse); #region pdf 변환 // 프린터 큐에 job이 생성될때까지 기다린다. while (pdf.cCountOfPrintjobs != 1) ; // 인쇄시작 pdf.cPrinterStop = false; // 인쇄가 완료될때 까지 기다린다. while (pdf.cCountOfPrintjobs != 0) ; #endregion #region 문서 닫기 및 PdfCreator 닫기 pdf.cPrinterStop = true; object doNotSaveChanges = false; object missing = Type.Missing; // 파워포인트 종료 pres.Close(); power.Quit(); // 컨버터 종료 pdf.cClose(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pdf); GC.Collect(); #endregion result.Success = true; result.OutputFileName = opt.AutosaveDirectory + opt.AutosaveFilename; result.ResultMessage = opt.AutosaveFilename + " 으로 변환이 성공 하였습니다"; } catch { result.Success = false; result.ResultMessage = pdf.cError.Description; } #endregion return result;}
8) OfficeToPDF에 외부에서 콜하는 public method를 생성한다.
/// <summary>/// pdf 컨버팅/// </summary>/// <param name="opt">컨버팅 옵션</param>/// <returns>결과값</returns>public PDFResult ConvertPDF(PDFOptions opt){ PDFResult result = null; result = InitializeCreator(opt); // 초기화 실패시 리턴 if (result.Success == false) return result; FileInfo info = new FileInfo(opt.SourceFileName); string ext = info.Extension.ToLower(); switch (ext) { case ".xls": case ".xlsx": result = ExcelToPDF(opt); break; case ".doc": case ".docx": result = WordToPDF(opt); break; case ".ppt": case ".pptx": result = PowerPointToPDF(opt); break; } return result;}
9) 마지막으로 Form의 버튼 클릭이벤트에 다음과 같이 코딩한다.
private void btnConvert_Click(object sender, EventArgs e){ OpenFileDialog openDlg = new OpenFileDialog(); string filter = "엑셀(2003) (*.xls)|*.xls|" ; filter += "엑셀(2007) (*.xlsx)|*.xlsx|" ; filter += "워드(2003) (*.doc)|*.doc|" ; filter += "워드(2007) (*.docx)|*.docx|" ; filter += "파워포인트(2003) (*.ppt)|*.ppt|" ; filter += "파워포인트(2007) (*.pptx)|*.pptx"; openDlg.Filter = filter; openDlg.FilterIndex = 1; openDlg.RestoreDirectory = true; if (openDlg.ShowDialog() != DialogResult.OK) return ; // 파일정보 System.IO.FileInfo info = new System.IO.FileInfo(openDlg.FileName) ; // 컨버팅 옵션 설정 PDFOptions opt = new PDFOptions() ; opt.SourceFileName = info.FullName ; opt.AutosaveDirectory = "C:\\"; opt.AutosaveFilename = info.Name.Replace(info.Extension, "") + ".pdf"; // 커서 설정 this.Cursor = Cursors.WaitCursor; // 파일 컨버팅 OfficeToPDF converter = new OfficeToPDF(); PDFResult result = converter.ConvertPDF(opt); // 커서 복원 this.Cursor = Cursors.Default; // 결과 메시지 표시 lblInfomation.Text = result.ResultMessage; MessageBox.Show(result.ResultMessage); }
자 이제 모든 개발이 끝났다..실행 해서 제대로 컨버팅이 되는지 확인해 본다.
이런식으로 된다면 성공이다.
안된다면 코드를 제대로 확인해 보는 수 밖에 ...
이거 좀 예전에 한거라 코드 보면서 다시 프로젝트를 생성하면서 했다.
첨으로 강좌(이런게 누군가에게 도움이 되었으면한다.)라는걸 웹공간에 올리려니 쪽팔리기도 하고
넘 간단한걸 강좌로 올린다고 욕할까봐 두렵기도 하지만 누군가는 필요한 코드가 될수도 있고
요즘 백업이란걸 잘 안해서 나도 잊어 버릴경우를 대비해서 써 봅니다.
*시간이 나고 요청이 오면 PDFCreator를 자동으로 셋업하는 프로젝트를 힘내서 맹글어 올려 볼께요..!! 모두 모두 홧팅~~