docx.브라우저에서 MS Word 파일이 작성될 때까지 js 사용

8011 단어 JavaScriptdocxdocx.js

개요


Word 파일(.docx)을 쓰기 위한 라이브러리 docx입니다.브라우저로 js를 이동하려면
https://docx.js.org/
브라우저도 정식으로 시작할 수 있지만 기본적으로 문서의 샘플은 모두 node입니다.js를 기반으로 한 데다가 제 기술이 부족해서 의외로 반했어요. 그래서 저는 모든 절차를 다 적어 놓을게요.

주안점

  • node.js에서 최종 파일 쓰기는 fs 모듈을 사용하는 것 같지만 브라우저에서 움직이지 않습니다. FileSaver.js 사용
  • 절차.


    npm의 초기화.대화에서 들을 수 있는 설정을 적당히 설정합니다.하지만 여기 이름은 docx라고 부르지 마세요.나중에 이름 충돌로 진행이 불가능할 겁니다.
    npm init
    
    docx 설치
    npm install docx --save-dev
    
    웹 패키지 설치
    npm install webpack webpack-cli --save-dev
    
    HTML 준비
    대체로 다음과 같은 느낌으로 웹 패키지로 다음에 쓰기 시작한 docx_browser.jsFileSaver를 불러오고 버튼으로 부르는 방법generate()을 불러옵니다.
    index.html
    <html>
        <head>
            <meta charset="utf-8">
            <title>docx sample</title>
            <!-- script by webpack -->
            <script src="docx_browser.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
        </head>
        <body>
            <h1>docx sample</h1>
            <button onclick="generate()">Generate DOCX</button>
        </body>
    </html>
    
    js의 준비
    https://docx.js.org/#/?id=basic-usage
    여기를 참고하여 아래 내용을 변경합니다(변경처의 평론이 추가되었습니다)
  • 행 삭제import * as fs from "fs";
  • 파일 쓰기 부분을 브라우저용으로 덮어쓰기
  • HTML에서 전체 주위function generate()를 호출할 수 있도록 전역 함수의 명령을 전역 함수
  • 에 추가generate()./src/main.js
    //不要コメントアウト
    //import * as fs from "fs";
    import { Document, Packer, Paragraph, TextRun } from "docx";
    
    //全体をfunctionで囲む
    function generate() {
        // Create document
        const doc = new Document();
    
        // Documents contain sections, you can have multiple sections per document, go here to learn more about sections
        // This simple example will only contain one section
        doc.addSection({
            properties: {},
            children: [
                new Paragraph({
                    children: [
                        new TextRun("Hello World"),
                        new TextRun({
                            text: "Foo Bar",
                            bold: true,
                        }),
                        new TextRun({
                            text: "\tGithub is the best",
                            bold: true,
                        }),
                    ],
                }),
            ],
        });
    
        // Used to export the file into a .docx file
        //ブラウザ動作用に書き換え
        /*
        Packer.toBuffer(doc).then((buffer) => {
                fs.writeFileSync("My Document.docx", buffer);
        });
        */
        //以下ブラウザ動作用
        Packer.toBlob(doc).then((blob) => {
            saveAs(blob, "output.docx");
            console.log("Document created successfully");
        });
    
    }
    
    //グローバル関数にする
    window.generate = generate;
    
    
    웹 패키지로 구축
    npx webpack --mode development ./src/main.js --output docx_browser.js
    
    그게 다야.

    실행 결과


    브라우저에 표시

    나열된 Word 파일

    작업 환경

  • IE 11은 움직이지 않는다.

  • 같은 이름의 프로그램 라이브러리도 몇 개 있고, 그 일본어 문장도 처리했지만, 여기에 소개된 것은 유일하게 유지보수된 것이다.
    유지 보수가 중지된 다른 라이브러리
    https://github.com/MrRio/DOCX.js
    https://github.com/stephen-hardy/DOCX.js
    다른 사용 가능한 라이브러리 (아직 시도하지 않음)
    https://github.com/guigrpa/docx-templates
    템플릿 파일을 다시 쓰는 방법으로 생성합니다.

    좋은 웹페이지 즐겨찾기