Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Microsoft PowerPoint 슬라이드를 HTML 파일로 ".files" 폴더 없이 저장하는 방법 (C# 코드)


아래와 같은 질문이 있군요.

C# 으로 PPT 파일을 html 로 변환시 생성되는 파일 문제 질문입니다.
; http://social.msdn.microsoft.com/Forums/ko-KR/visualcsharpko/thread/37e877cb-ec06-474c-9429-b39dcd5655c4

질문자의 설명대로 PowerPoint 슬라이드를 HTML 파일로 저장하려는 경우, 내부에 사용된 이미지 파일 등으로 인해 "[파일명].files"와 같은 특수 폴더가 함께 생기면서 저장이 됩니다.

예를 들어, 다음은 test.pptx 파일을 HTML 파일로 저장한 경우에 생성된 결과물입니다.

ppt_save_0.png

보시는 것처럼, test.html 파일이 생겼고 그와 함께 "test.files"라는 폴더가 연결되어 그 하위에 이미지 파일 등이 저장되어 있습니다.

사실, 마이크로소프트 입장에서는 나름 신경써서 이런 구조를 만들어 둔 것입니다.

Connected Files
; https://docs.microsoft.com/en-us/windows/win32/shell/manage#connected-files

Operations on an HTML file or folder apply to similarly named folder or HTML file
; http://support.microsoft.com/kb/252721/en-us

"Connected Files"라고 해서, html 파일 하나를 지우면 같이 연결된 ".files" 폴더가 삭제되고, 또는 이동을 하게 되면 ".files" 폴더도 함께 이동되어 문서가 안전하게 다뤄질 수 있도록 해주는 기술입니다.

음... 그렇다고는 하지만, 역시 현업에서는 그냥 같은 폴더에 함께 출력해 주는 것이 선호될 수도 있을 텐데 그에 대한 배려까지 해주지 않은 것이 좀 아쉬움일 수 있겠군요. ^^




문제 해결은, 일단 PowerPoint의 수준에서는 해결할 수 있는 저장 옵션이 없습니다.

PpSaveAsFileType Enumeration
; https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/bb251061(v=office.12)

하지만, 수작업으로 보정해 주는 것은 간단합니다.

왜냐하면, 결국 출력된 test.html 파일 안에는 "test.files" 폴더에 담긴 파일들이 'path'로 연결되어 있을 것이기 때문에 그에 대한 문자열 경로만 수정해서 저장해 주면 되기 때문입니다.

정말 잘 되는지 테스트를 한번 해볼까요? ^^

일단, PowerPoint에 대한 참조를 추가하고,

ppt_save_1.png

Visual Studio 2010 / .NET 4.0인 경우 "Embed Interop Types" 옵션을 False로 바꿔줍니다.

ppt_save_2.png

이어서, 질문자의 코드 대로 프로그램을 만들면 "html" 파일로 내보내기가 가능합니다.

static void Main(string[] args)
{
    string pathFileName = Path.Combine(Environment.CurrentDirectory, "test.pptx");
    string slideImagePath = Path.Combine(Environment.CurrentDirectory, "test.html");

    File.Delete(slideImagePath);

    {
        Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
        Microsoft.Office.Interop.PowerPoint.Presentations ppPresentations = ppApp.Presentations;
        Microsoft.Office.Interop.PowerPoint.Presentation prsPres 
            = ppPresentations.Open(pathFileName,
                MsoTriState.msoTrue,
                MsoTriState.msoFalse,
                MsoTriState.msoFalse);
        prsPres.SaveAs(slideImagePath, 
            Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoFalse);

        Marshal.ReleaseComObject(prsPres);
        Marshal.ReleaseComObject(ppPresentations);
        Marshal.ReleaseComObject(ppApp);
    }

    string pathToHtml = Path.Combine(Environment.CurrentDirectory, "html");
    MergeFiles(slideImagePath, pathToHtml);
}

그다음은 이렇게 내보내진 "test.files" 폴더의 내용과 html 파일을 하나의 폴더로 병합해주면 되는데요. 코드는 그렇게 복잡하지 않습니다.

private static void MergeFiles(string slideImagePath, string pathToHtml)
{
    string dirPath = Path.GetDirectoryName(slideImagePath);
    string subDirName = Path.GetFileNameWithoutExtension(slideImagePath);

    string subFilesPath = subDirName + ".files";

    string oldDirPath = Path.Combine(dirPath, subFilesPath);
    string newDirPath = Path.Combine(dirPath, pathToHtml);

    Directory.CreateDirectory(newDirPath);

    // .files 폴더 내용을 복사하고,
    foreach (string txt in Directory.GetFiles(oldDirPath))
    {
        string fileName = Path.GetFileName(txt);
        string targetFilePath = Path.Combine(newDirPath, fileName);
        File.Copy(txt, targetFilePath, true);
    }

    // HTML 파일 내용에서 ...files/... 인 경로를 모두 삭제
    string text = File.ReadAllText(slideImagePath);
    string replaced = text.Replace(subFilesPath + "/", string.Empty);

    string newHtmlPath = Path.Combine(newDirPath, Path.GetFileName(slideImagePath));
    File.WriteAllText(newHtmlPath, replaced);

    // .files 폴더와 연결된 html 파일을 삭제
    Directory.Delete(oldDirPath, true);
    File.Delete(slideImagePath);
}

일단, 문자열 치환 기능은 string.Replace로 단순하게 했습니다. 이 때문에 만약 본문에 "test.files/"라는 문자열이 있다면 없어질 수 있는데요. 확률이 낮기 때문에 쓸만한 수준입니다. (물론, 확실하게 하려면 HTML 파일을 XML로 로드해서 href 속성에 있는 경로만을 수정하도록 범위를 좁힌다면 확실한 결과물을 얻을 수 있습니다.)

이렇게 해서 실행하면 다음과 같이 하나의 폴더에 출력이 병합되고,

ppt_save_3.png

웹 브라우저로 test.html 파일을 보면 정상적으로 슬라이드 내용이 출력되는 것을 확인할 수 있습니다.

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.

부가적으로, "Connected Files"에 대한 기능을 레지스트리를 통해서 제어하는 것이 가능하다고 합니다.

JSI Tip 3841. What is the Windows 2000 Connected File feature?
; http://www.windowsitpro.com/article/tips/jsi-tip-3841-what-is-the-windows-2000-connected-file-feature-

클라이언트 측의 레지스트리 값을 함부로 건드리는 것은 좋지 않지만... 특정 머신에서만 이런 동작을 하는 거라면 나름 유용하게 씌여질 날이 오겠지요. ^^

키 경로: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer
이름: NoFileFolderConnection
값 형식: REG_DWORD
값: 1 (1이면, Connected Files 기능 해제)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/12/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13466정성태11/29/20232688닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232453개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232551닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232431오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232430오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232511닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232448닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232484닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232491닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232386VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232727닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232630닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232931닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232382오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232494닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232619닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232423닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232543개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232898닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232784닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232723닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20233032Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232752닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232806개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232578개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232947닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...