LoginSignup
3
4

More than 5 years have passed since last update.

VF帳票出力Tips Word編

Last updated at Posted at 2018-03-06

VF で Word ファイルを出力する方法をかんたんにまとめました。

VF で Word ファイルを出力する

Salesforce で Word ファイルを出力したいという要望がごくたまにあると思います。

主な対応としては次の2通りがあります。

  • htmlを利用して拡張子.docファイルとして出力する(縦書きの出力不可)
  • VBScript と ActiveX を利用して、IE で Wordファイルを出力する(縦書きの出力可能)

上記以外の方法で Word ファイルを出力する方法を紹介します。

docxtemplater を利用する

ブラウザのみでも動作するので、Visualforce ページでも利用することが可能です。
以下の document サイトのサンプルをVF ページで実装してみました。
テンプレートとして利用する Word ファイルは静的リソースにアップしています。

以下はサンプルコードです。

<apex:page id="page" docType="html-5.0" standardStylesheets="false" showHeader="false" sidebar="false" applyBodyTag="false" applyHtmlTag="false">
<html>
    <script src="{!URLFOR($Resource.docxtemplater,'docxtemplater/js/docxtemplater-latest.min.js')}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.6.1/jszip.min.js"></script>
    <script src="{!URLFOR($Resource.docxtemplater,'docxtemplater/js/file-saver.min.js')}"></script>
    <script src="{!URLFOR($Resource.docxtemplater,'docxtemplater/js/jszip-utils.js')}"></script>
    <script>
    function loadFile(url,callback){
        JSZipUtils.getBinaryContent(url,callback);
    }
    loadFile("https://c.ap4.visual.force.com/resource/1520307484000/tag_example",function(error,content){
        if (error) { throw error };
        var zip = new JSZip(content);
        var doc=new Docxtemplater().loadZip(zip)
        doc.setData({
            first_name: 'John太郎',
            last_name: 'Doe',
            phone: '0652455478',
            description: 'New Website'
        });

        try {
            // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
            doc.render()
        }
        catch (error) {
            var e = {
                message: error.message,
                name: error.name,
                stack: error.stack,
                properties: error.properties,
            }
            console.log(JSON.stringify({error: e}));
            // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
            throw error;
        }

        var out=doc.getZip().generate({
            type:"blob",
            mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        }) //Output the document using Data-URI
        saveAs(out,"output.docx")
    })
    </script>
</html>
</apex:page>

docxtemplater で出来ること

  • マルチバイト文字(日本語)を利用することが可能
  • テンプレートファイルに画像を利用することが可能
  • 縦書きのレイアウトで出力することが可能

上記以外にもpptファイルに対応していたり、ループ処理でテーブルレイアウトの出力にも対応しているようです。

Salesforce の差し込み印刷の代わりに利用できるかもしれません。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4