CODEKILLER

반응형

▶ Word 파일의 경로를 이용하여 PDF파일로 바꾸는 예제입니다.

 

▶ 사용하는 참조 (Microsoft.Office.Interop.Word)

▶ 사용하는 참조 (Office)

/// <summary>
/// 워드 파일을 PDF파일로 변환합니다.
/// </summary>
/// <param name="sourceFilePath">word file path</param>
/// <param name="targetFilePath">pdf file path</param>
/// <returns></returns>
public static RET_VAL WordToPDF(string sourceFilePath, string targetFilePath)
{
    RET_VAL result = RET_VAL.Pass;

    Microsoft.Office.Interop.Word.Application docApp = null;
    Document document = null;

    try
    {               
        docApp = new Microsoft.Office.Interop.Word.Application();
        docApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        docApp.ScreenUpdating = false;                
        docApp.Visible = false;

        object oSouceFilePath = sourceFilePath as object;

        object oFalse = false;
        object oReadOnly = true;
        object oMissing = System.Reflection.Missing.Value;

		// word 파일을 Document Open 합니다.
        document = docApp.Documents.Open(ref oSouceFilePath, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

        if (document != null)
        {
            WdStatistic stat = WdStatistic.wdStatisticPages;
            
            // 페이지의 Count를 조회합니다.
            int pageCount = document.ComputeStatistics(stat, ref oMissing);

			// 페이지 Limit에 따른 변환여부를 결정합니다.
            if (pageCount >= MaxPageLimit)
            {
                result = RET_VAL.OverPage;
            }
            else
            {
                object oTargetFilePath = targetFilePath as object;
                object oFileFormat = WdSaveFormat.wdFormatPDF;

				// pdf파일로 변환합니다.
                document.SaveAs(ref oTargetFilePath, ref oFileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing
                    , ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            }

            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
            document.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
            document = null;

        }
        else
        {
            result = RET_VAL.Fail;
        }
        docApp.ScreenUpdating = true;    
        docApp.Quit();
        docApp = null;
    }
    catch (Exception ex)
    {
        try
        {
            if (document != null)
            {
                document.Close();
                document = null;
            }
        }
        catch
        {
        }
        if (docApp != null)
        {
            docApp.ScreenUpdating = true; 
            docApp.Quit();
            docApp = null;
        }
        result = RET_VAL.Fail;
    }

    return result;
}
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band