1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Salesforceブラウザ別タブでPDFファイルを表示する

Last updated at Posted at 2021-10-18

Salesforceブラウザ別タブでPDFファイルの表示について、本文にて整理します。

Visualforceの場合

◆静的リソースのPDFをブラウザの別タブで表示する場合、apex:outputLinkタグを利用して、静的リソースを直接開くことが可能です。

<apex:outputLink value="{!URLFOR($Resource.PDFFileName)}" />

◆ContentVersionオブジェクトに登録されるPDFをブラウザの別タブで表示する場合、Visualforce側に特に制限がないため、通常のJSを利用して実現できることはVisualforce側でも実現できることです。
以下は実装列です。

Apex側の実装.cls
@RemoteAction
global static List<String> getPdfData(String cvId) {
    
    // コンテンツバージョンを取得
    ContentVersion cv = [SELECT Id, PathOnClient, IsLatest, Title, FileExtension, VersionData
              	FROM ContentVersion WHERE Id =: cvId];
    List<String> result = new List<String>();
    result.add(EncodingUtil.base64Encode(cv.VersionData));
    result.add(cv.PathOnClient);
    return result;
}

ページ側の実装について、いくつかの案があります。

ページ側の実装.page
{!$RemoteAction.ApexCtrl.getPdfData}(cvId, function(result, event){
    if(event.status) {

        // 案①
        let _pdfWindow = window.open("");
        _pdfWindow.document.write(
            "<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
            encodeURI(result[1]) + "'></iframe>"
        );
        _pdfWindow.document.title = result[0];

       // 案②
       var byteCharacters = atob(result[1]);
       var byteNumbers = new Array(byteCharacters.length);
       for (var i = 0; i < byteCharacters.length; i++) {
           byteNumbers[i] = byteCharacters.charCodeAt(i);
       }
       var byteArray = new Uint8Array(byteNumbers);
       var file = new Blob([byteArray], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
       window.open(fileURL);

       // 案③:PDF.js
       「PDF.js」を利用してポップアップ画面でPDFを表示することもできます。詳細の実装に対し、以下のサンプルを参照してください。
       https://mozilla.github.io/pdf.js/examples/
    }
});

LWCの場合

カスタムLWCコンポーネントに対し、PDFをブラウザの別タブで表示することができないです。
上記の案①、②を利用して、LWCに実装されると、「Unsupported mime type」、「securewindow.open supports http:, https:, mailto: schemes and relative urls」のエラーが発生してしまう。
原因:カスタムLWCが「ユーザモード」として実行され、JSのドキュメント又はWindowsオブジェクトのアクセス権限がないため。
https://developer.salesforce.com/blogs/developer-relations/2016/04/introducing-lockerservice-lightning-components

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?