@grapecity/gcpdfviewer

GrapeCity Documents PDF Viewer

Usage no npm install needed!

<script type="module">
  import grapecityGcpdfviewer from 'https://cdn.skypack.dev/@grapecity/gcpdfviewer';
</script>

README

GrapeCity Documents PDF Viewer

日本語

A full-featured JavaScript PDF viewer and editor that comes with GrapeCity Documents for PDF.

GrapeCity Documents PDF Viewer (GcDocs PDF Viewer, GcPdfViewer) is a fast, modern JavaScript based PDF viewer and editor that runs in all major browsers. The viewer can be used as a cross platform solution to view (or modify - see Support API below) PDF documents on Windows, MAC, Linux, iOS and Android devices. GcPdfViewer is included in GrapeCity Documents for PDF (GcPdf) - a feature-rich cross-platform PDF API library for .NET Core.

Support API is a server-side ASP.​NET Core library that ships as C# source code, and allows you to easily set up a server that uses GcPdf to provide PDF modification features to GcPdfViewer. When connected to Support API, GcPdfViewer can be used as a PDF editor to save filled PDF forms, remove sensitive content, edit annotations and forms, and more.

See docs/index.html for GcPdfViewer client API documentation.

Product highlights:

  • Works in all modern browsers, including IE11, Edge, Chrome, FireFox, Opera, Safari
  • When connected to GcPdf on the server via Support API, provides:
    • Customizable and mobile-friendly form filler
    • Real-time collaboration mode
    • Annotation and form editors
    • Quick edits using secondary toolbars
    • PDF redaction
    • Signature verification
    • Other editing features
  • Works with frameworks such as React, Preact, Angular
  • Supports form filling; filled forms can be printed or form data can be submitted to the server
  • Supports XFA (XML Forms Architecture) forms
  • Provides caret for text selection/copy, including vertical and RTL texts
  • Includes thumbnails, text search, outline, attachments, articles, layers and structure tags panels
  • Allows opening PDF files from local disks
  • Supports annotations including text, free text, rich text etc.
  • Supports redact annotations (including appearance streams), allows user to hide or show redacts
  • Supports sound annotations
  • Allows rotating and printing the rotated document
  • Supports article threads navigation
  • Fully supports file attachments (both attachment annotations and document level attachments)
  • Comes with several themes, new custom themes can be added
  • Supports external CMaps
  • ...and more.

[3.0.19] - 25-Jan-2022

Added

  • Added the ability to specify authentication or other HTTP headers in the open() method. (DOC-3998)
  // Example: specify basic access authentication and custom headers:
  viewer.open("http://example.com//pdfs/GetPdf?file=HelloWorld.pdf", { 
    headers: { 
      "Authorization": "Basic " + btoa(unescape(encodeURIComponent("USERNAME:PASSWORD"))),
      "CustomHeader": "Custom header value"
    }
  });
  • Added the ability to specify authentication or other HTTP headers in SupportApi requests. (DOC-3998)
  // Example: specify basic access authentication and custom headers:
  const viewer = new GcPdfViewer("#viewer", {
    supportApi: {
      apiUrl: "192.168.0.1/support-api",
      requestInit: { 
        headers: {
          "Authorization": "Basic " + btoa(unescape(encodeURIComponent("USERNAME:PASSWORD"))),
          "CustomHeader": "Custom header value"
        }
      }
    }
  });

Fixed

  • [Editor] Text added in the free text annotation editor disappears on resizing the annotation. (DOC-3988)

[3.0.18] - 24-Jan-2022

Fixed

  • Undo history should be cleared by the close() method. (DOC-3989)

[3.0.17] - 21-Jan-2022

Added

  • [Form Editor] "Editable" property added to combo boxes. (DOC-3947)
  • [Form Editor] New values added to "Tab order" property: "Annotations" and "Widgets". (DOC-3668)
  • Added ability to close the current document. (DOC-3981)
  // Usage example:
  await viewer.close();

Fixed

  • Incorrect tab cycle for an editable combo box. (DOC-3967)
  • Tab order differs from Adobe Acrobat Reader in some cases. (DOC-3668)
  • [Form Editor] Cannot reset the "Tab order" property to "Not specified". (DOC-3968)
  • [Editor] The Backspace key does not work in the free text annotation editor. (DOC-3983)
  • [Editor] If a new page is inserted and the document is saved, the tab order of following pages is incorrect. (DOC-3985)

[3.0.13] - 22-Dec-2021

Added

  • Added support for editable combo boxes. (DOC-3947)
  • [XFA forms] Added the ability to select/copy text content. (DOC-3917)
  • [Editor] Remember last used editor values. (DOC-3925)
    New settings added to the "editorDefaults" option: "rememberLastValues" and "lastValueKeys". If "rememberLastValues" is set to true or undefined, the last used property values will be used as default values for new annotations. "lastValueKeys" specifies which properties will be remembered.
  // The default value of lastValueKeys:
  ["appearanceColor", "borderStyle", "color", "interiorColor", "backgroundColor", "borderColor", "opacity", "textAlignment", "printableFlag", "open",
  "lineStart", "lineEnd", "markBorderColor", "markFillColor", "overlayFillColor", "overlayText", "overlayTextJustification", "newWindow", "calloutLineEnd", "fontSize",
  "fontName", "name", "readOnly", "required"]
  // Example: turn remembering last used values off:
  var viewer = new GcPdfViewer("#root", { editorDefaults: { rememberLastValues: false } });
  // Example: remember only the borderStyle property:
  var viewer = new GcPdfViewer("#root", { editorDefaults: { rememberLastValues: true, lastValueKeys: ["borderStyle"] } });
  • [Android] Added support for zooming using pinch gesture. (DOC-3424, ARD-2508)

Changed

  • Japanese localization strings updated.

Fixed

  • [iPad] PDF will not render after max zooming when iPad is running in Desktop mode. (DOC-3765)
  • [iOS][Android] The main toolbar collapses when the secondary toolbar is clicked. (DOC-3843)
  • [Editor] Method showSecondToolbar does not activate editor mode correctly. (DOC-3892)
  • [Editor] Incorrect undo / redo behavior when editing ink annotations. (DOC-3924)
  • Incorrect zoom controls behavior. (DOC-3929)

[3.0.10] - 25-Nov-2021

Changed

  • Breaking change: All public APIs that used page numbers now use zero-based page indices. (DOC-3536)
  • PDF.js library was updated from v2.0.943 to v2.10.377, see PDF.js Release Notes.
  • Method goToPageNumber deprecated, use goToPage method or pageIndex property instead. (DOC-3536)
  • By default, radio buttons and checkboxes now do not use predefined appearances from the PDF. Use the fieldsAppearance option to revert to the old behavior:
  var viewer = new GcPdfViewer("#root", { fieldsAppearance: { radioButton: "Predefined", checkBoxButton: "Predefined" } });
  • [SupportApi client] The ping() method has been deprecated and is no longer used; instead, the serverVersion() method is used.
  • Properties SubmitForm/ResetForm renamed to submitForm/resetForm. (DOC-3379)

Added

  • Added ability to edit document without switching to Annotation Editor or Form Editor modes. (DOC-3169)
  • Added support for second horizontal toolbar.
  • Added secondary editing toolbars to the main viewer toolbar: "Text tools", "Draw tools", "Attachments and stamps", "Form tools", "Page tools".
    Use secondToolbarLayout to control which toolbars are enabled.
    // Example: specify custom second toolbar layout:
    viewer.secondToolbarLayout = { "text-tools": ['edit-text', 'edit-free-text'] };
    
  • Added API to display a custom second toolbar. (DOC-3170)
    // Example: create custom second toolbar with key "custom-toolbar-key":
    var React = viewer.getType("React");
    var toolbarControls = [React.createElement("label", null, "Custom toolbar"),
    React.createElement("button", { onClick: () => { alert("Execute action."); }, title: "Action title" }, "Action")];
    // Register custom second toolbar for key "custom-toolbar-key":
    viewer.options.secondToolbar = {
     render: function(toolbarKey) {
       if(toolbarKey === "custom-toolbar-key")
         return toolbarControls;
       return null;
     }
    };
    // Show custom second toolbar:
    viewer.showSecondToolbar("custom-toolbar-key");
    
  • Added Light and Dark themes. (DOC-3169)
  • Support page content accessibility for tagged PDFs containing logical structure information for screen readers.
  • Added ability to show the structure tree of tagged PDFs. (DOC-3131)
    // Use addStructureTreePanel method to add the appropriate panel:
    const viewer = new GcPdfViewer(selector);
    viewer.addStructureTreePanel();
    await viewer.open("sample.pdf");
    
    // Use structureTree to access available structure tree data:
    const viewer = new GcPdfViewer(selector);
    await viewer.open("sample.pdf");
    const structureTree = await viewer.structureTree;
    if(structureTree) {
     console.log(structureTree);
    }
    
  • Added goToPage method: navigate to the page with a specified 0-based index.
    // Example: go to the first page:
    viewer.goToPage(0);
    
  • Added option maxCanvasPixels: maximum supported canvas size in pixels, i.e. width * height. Undefined or -1 means no limit. If the canvas scaling exceeds maxCanvasPixels, the CSS scaling is used instead of re-rendering the page to the canvas. (DOC-3765)
  • Added the ability to use GET method to submit a form.
    // Using GcPdf to create an ActionSubmitForm to submit a form using the GET method:
    var actionSubmit = new ActionSubmitForm("/");
    actionSubmit.SubmitFormat = ActionSubmitForm.SubmitFormatType.HtmlForm;
    actionSubmit.HtmlFormFormat = ActionSubmitForm.HtmlFormFormatFlags.GetMethod;
    var btnSubmit = new PushButtonField();
    btnSubmit.Widget.Rect = new RectangleF(50, 100, 100, 50);
    btnSubmit.Widget.ButtonAppearance.Caption = "Submit";
    btnSubmit.Widget.Page = page;
    btnSubmit.Widget.Events.Activate = actionSubmit;
    
  • Action reset: added support for FieldNames, ExcludeSpecifiedFields and Next properties. (DOC-3379)
  • Added new option fieldsAppearance - specifies how form fields are rendered. (DOC-3537)
    Use this option to customize rendering of form fields. Available appearance rendering types:
    • "Custom" - Default. The custom appearance has some improvements over the web appearance, for example you can specify background and border colors.
    • "Web" - Standard form field appearance using native platform styling. See https://developer.mozilla.org/en-US/docs/Web/CSS/appearance for details.
    • "Predefined" - Predefined appearance stream from PDF when available. If the appearance stream is not available, custom appearance will be used.
    // Example 1: Use platform-native styling for radio and checkbox buttons.
    var viewer = new GcPdfViewer("#root", { fieldsAppearance: { radioButton: "Web", checkBoxButton: "Web" } });
    
    // Example 2: Use predefined appearance stream for radio buttons:
    var viewer = new GcPdfViewer("#root", { fieldsAppearance: { radioButton: "Predefined" } });
    
  • Added enableXfa option: render XFA (XML Forms Architecture) forms if any; the default is true. (DOC-3681)
    // Example: turn XFA forms off:
    var viewer = new GcPdfViewer(selector, { enableXfa: false });
    
  • Added requireTheme option. Use this option to apply a built-in CSS theme, this will inject the theme styles directly into the page head. Note that only a known built-in theme can be specified, otherwise the viewer will fail to load. Available built-in themes: "viewer", "dark", "dark-yellow", "gc-blue", "light", "light-blue". This option takes precedence over the "theme" option which can be used to specify a custom theme.
    // Example:
    var viewer = new GcPdfViewer(selector, { 
         requireTheme: "light"
    });
    
  • Added onThemeChanged event: raised when the user changes the viewer theme.
    // Example:
    var viewer = new GcPdfViewer(selector, { 
         requireTheme: localStorage.getItem('demo_theme') || 'viewer'
     });
     viewer.addDefaultPanels();
     viewer.onThemeChanged.register(function(args) {
       localStorage.setItem('demo_theme', args.theme);
     });
    
  • Added onInitialized option: the onInitialized handler will be called immediately after the viewer is instantiated.
    // Example:
    var viewer = new GcPdfViewer("#root", { 
      onInitialized: (viewer)=> { 
        // put viewer initialization code here. 
      } 
    });
    

Fixed

  • Multiple bug fixes.

See CHANGELOG.​md for detailed release notes.

See it in action

Installation

To install the latest release version:

npm install @grapecity/gcpdfviewer

To install from the zip archive:

Go to https://www.grapecity.com/download/documents-pdf and follow the directions on that page to get your 30-day evaluation and deployment license key. The license key will allow you to develop and deploy your application to a test server. Unzip the viewer distribution files (list below) to an appropriate location accessible from the web page where the viewer will live.

Viewer zip includes the following files:

  • README.​md (this file)
  • CHANGELOG.​md
  • gcpdfviewer.js
  • gcpdfviewer.worker.js
  • package.json
  • index.html (sample page)
  • Theme files:
    • themes/dark-yellow.css
    • themes/dark-yellow.jscss
    • themes/light-blue.css
    • themes/light-blue.jscss
    • themes/viewer.css
    • themes/viewer.jscss
  • Predefined CMap files for Chinese, Japanese, or Korean text output:
    • resource/bcmaps/*.bin
  • TypeScript declaration files:
    • typings/.

Documentation

Online documentation is available here.

Licensing

GrapeCity Documents PDF Viewer is a commercially licensed product. Please visit this page for details.

Getting more help

GrapeCity Documents PDF Viewer is distributed as part of GrapeCity Documents for PDF. You can ask any questions about the viewer, or report bugs using the Documents for PDF public forum.

More details on using the viewer

Adding the viewer to an HTML page:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <!-- Limit content scaling to ensure that the viewer zooms correctly on mobile devices: -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="theme-color" content="#000000" />
    <title>GrapeCity Documents PDF Viewer</title>
    <script type="text/javascript" src="lib/gcpdfviewer.js"></script>
    <script>
        function loadPdfViewer(selector) {
            var viewer = new GcPdfViewer(selector,
              {
                /* Specify options here */
                renderInteractiveForms: true
              });
            // Skip the 'report list' panel:
            // viewer.addReportListPanel();
            viewer.addDefaultPanels();
            // Optionally, open a PDF (will only work if this runs from a server):
            viewer.open('HelloWorld.pdf');
            // Change default viewer toolbar:
            viewer.toolbarLayout.viewer.default = ['$navigation', '$split', 'text-selection', 'pan', '$zoom', '$fullscreen',
              'save', 'print', 'rotate', 'view-mode', 'doc-title'];
            viewer.applyToolbarLayout();
        }
    </script>
  </head>
  <body onload="loadPdfViewer('#root')">
    <div id="root"></div>
  </body>
</html>

How to license the viewer:

Set the GcPdfViewer Deployment key to the GcPdfViewer.License property before you create and initialize GcPdfViewer. This must precede the code that references the js files.

  // Add your license
  GcPdfViewer.LicenseKey = 'xxx';
  // Add your code
  const viewer = new GcPdfViewer("#viewer1", { file: 'helloworld.pdf' });
  viewer.addDefaultPanels();

Support API

Support API is a server-side library that ships as C# source code with GcPdf. The full source code is also included with all GcPdfViewer samples that can be downloaded from the GcPdfViewer demo site. The code can be built to use in an ASP.​NET Core or a WebForms application (see #if WEB_FORMS in the sources). When GcPdfViewer is connected to Support API, its editing features are enabled. The edits done on the client are accumulated, and when the user clicks 'save', the document and the edits are sent to the server, the edits are applied, and the modified PDF is sent back to the client.

To set up a server that provides Support API in an ASP.​NET Core app (ASP.​NET Core 3.0 or later is required):

  • Download any of the samples from the GcPdfViewer demo site (e.g. Edit PDF).
  • Unpack the downloaded .zip into a directory.
  • In that directory you will find a WebApi.zip file containing the full SupportApi C# sources (WebApi.zip/WebApi/SupportApi), plus an ASP.​NET Core (WebApi.zip/WebApi/AspNetCore.sln) and a WebForms (WebApi.zip/WebApi/WebForms.sln) sample projects.
  • Running the run.cmd batch file in the sample directory will unpack the SupportApi files, build and start the service, build and run the sample and open the sample URL (http://localhost:3003) in your default browser.
  • The directory WebApi.zip/WebApi/SupportApi and everything inside it is the Support API library. It can be used as is in your own projects.
  • WebApi.zip/WebApi/SupportApi/Controllers/GcPdfViewerController.cs contains the API entry points. Check it out to see what operations are available.
  • For more details check out the readme.​md that is included in all downloaded viewer samples.

NOTE that you will need a GrapeCity Documents for PDF Professional license to use Support API in your apps.

Keyboard shortcuts

Viewer mode

  • Ctrl + - zoom in
  • Ctrl - - zoom out
  • Ctrl 0 - zoom to 100%
  • Ctrl 9 - zoom to window
  • Ctrl A - select all
  • R - rotate clockwise
  • Shift R - rotate counterclockwise
  • H - enable pan tool
  • S - enable selection tool
  • V - enable selection tool
  • Ctrl O - open local PDF
  • Ctrl F - text search
  • Ctrl P - print
  • Home - go to start of line
  • Ctrl Home - go to start of document
  • Shift Home - select to start of line
  • Shift Ctrl Home - select to start of document
  • End - go to end of line
  • Ctrl End - go to end of document
  • Shift End - select to end of line
  • Shift Ctrl End - select to end of document
  • Left - go left
  • Shift Left - select left
  • Alt Left - go back in history
  • Right - go right
  • Shift Right - select right
  • Alt Right - go forward in history
  • Up - go up
  • Shift Up - select up
  • Down - go down
  • Shift Down - select down
  • PgUp - page up
  • PgDown - page down
  • Shift PgUp - select page up
  • Shift PgDown - select page down

Editing modes

  • Delete - delete selected annotation/field
  • Esc - unselect annotation/field
  • Ctrl Z - undo
  • Ctrl Y - redo
  • Ctrl Shift Z - redo

Toolbar items

The default viewer toolbar items layout (items starting with ' are inherited from the base viewer, other items are PDF viewer specific.):

['open', '$navigation', '$split', 'text-selection', 'pan', '$zoom', '$fullscreen', 'rotate', 'view-mode', 'theme-change', 'download', 'print', 'save', 'hide-annotations', 'doc-title', 'doc-properties', 'about']

The full list of the PDF-viewer specific toolbar items:

'text-selection', 'pan', 'open', 'save', 'download', 'print', 'rotate', 'theme-change', 'doc-title', 'view-mode', 'single-page', 'continuous-view'

The full list of base viewer toolbar items:

'$navigation' '$refresh', '$history', '$mousemode', '$zoom', '$fullscreen', '$split'

You can get default base viewer items by using the getDefaultToolbarItems() method, e.g.:

const toolbar: Toolbar = viewer.toolbar;
let buttons = toolbar.getDefaultToolbarItems();
buttons = buttons.filter(b => b !== '$refresh');

To specify a custom set of toolbar items, use the toolbarLayout property and applyToolbarLayout() method, e.g.:

viewer.toolbarLayout.viewer = {
  default: ["$navigation", 'open', '$split', 'doc-title'],
  fullscreen: ['$fullscreen', '$navigation'],
  mobile: ["$navigation", 'doc-title']
};
viewer.toolbarLayout.annotationEditor = {
  default: ['edit-select', 'save', '$split', 'edit-text'],
  fullscreen: ['$fullscreen', 'edit-select', 'save', '$split', 'edit-text'],
  mobile: ['$navigation']
};
viewer.toolbarLayout.formEditor = {
  default: ['edit-select-field', 'save', '$split', 'edit-widget-tx-field', 'edit-widget-tx-password'],
  fullscreen: ['$fullscreen', 'edit-select-field', 'save', '$split', 'edit-widget-tx-field', 'edit-widget-tx-password'],
  mobile: ['$navigation']
};
viewer.applyToolbarLayout();

Here is an example of how to create your own custom toolbar button:

const toolbar: Toolbar = viewer.toolbar;
toolbar.addItem({
  key: 'my-custom-button',
  iconCssClass: 'mdi mdi-bike',
  title: 'Custom button',
  enabled: false,
  action: () => {
    alert("Custom toolbar button clicked");
  },
  onUpdate: (args) => ({ enabled: viewer.hasDocument }),
});
viewer.toolbarLayout.viewer.default =  ['$navigation', 'my-custom-button'];
viewer.applyToolbarLayout();

Using the viewer in Preact

Add a reference to the viewer script.

<body>
  <script type="text/javascript" src="/lib/gcpdfviewer/gcpdfviewer.js"></script>
  ...

Add the placeholder to your App template, e.g.:

<section id="pdf"></section>

Render the viewer:

let viewer = new GcPdfViewer('section#pdf');
viewer.addDefaultPanels();

GrapeCity PDF ビューワ(日本語版)

GrapeCity PDF ビューワ (GcPdfViewer) は、主要なブラウザで動作する、JavaScriptベースのPDFビューワおよびエディタです。Windows、MAC、Linux、iOS、Androidなどのデバイス上でPDFドキュメントを表示 (または編集 - 下記の Support API を参照) するためのクロスプラットフォームソリューションとして使用することができます。 なお、本PDFビューワは、クロスプラットフォーム環境にてPDFを作成・編集できるAPIライブラリ DioDocs for PDF に付属する製品となります。

SupportAPI は、C#のソースコードにて提供されるサーバーサイドのASP.​NET Coreライブラリであり、DioDocs for PDFを使用してPDFビューワにPDFの編集機能を提供するサーバを簡単に構築することができます。Support API に接続すると、PDFビューワをPDFエディタとして使用し、記入済みのPDFフォームの保存、機密コンテンツの削除、注釈やフォームの編集などを行うことができます。

PDFビューワのクライアントAPIの詳細については、こちらをご参照ください。

製品の特徴:

  • IE11、Edge、Chrome、FireFox、Opera、Safariを含むすべての最新ブラウザで動作します
  • Support API 経由で DioDocs for PDF に接続した場合、以下の機能を提供します:
    • カスタマイズ可能でモバイルフレンドリーなフォームフィラー
    • リアルタイムなコラボレーションモード
    • 注釈とフォームの編集
    • セカンドツールバーを使用したクイック編集
    • PDFコンテンツの墨消し
    • 署名の検証
    • その他の編集機能
  • React、Preact、Angular などのフレームワークで動作します
  • フォームの入力に対応:記入済みフォームの印刷や、フォームデータのサーバへの送信にも対応しています
  • XFA(XML Forms Architecture)フォームに対応しています
  • 縦書きテキストや右横書きテキストを含む、テキストの選択/コピーのためのキャレットを提供します
  • サムネイル、テキスト検索、ブックマーク、添付ファイル、アーティクル、レイヤー、構造ツリーのパネルが含まれます
  • ローカルディスクからPDFファイルを開くことができます
  • テキスト、フリーテキスト、リッチテキストなどの注釈に対応しています
  • 墨消し注釈(APストリームを含む)に対応し、墨消しの表示・非表示が可能です
  • 音声注釈に対応しています
  • 文書の回転や、回転させた文書の印刷が可能です
  • アーティクルのスレッドナビゲーションに対応しています
  • 添付ファイル(添付ファイル注釈と文書レベルの添付ファイルの両方)に完全に対応しています
  • 複数のテーマがすでに備わっており、さらに新しいカスタムテーマを追加することも可能です
  • 外部のCMapに対応しています
  • その他、様々な機能を提供しています

リリースノート

日本語版として動作を保証しているのは、リリースノートに記載しているバージョンのみとなります。

[3.0.13] - 2022年2月9日

重大な変更

  • ページ番号を使用するすべての API にて、0から始まるページインデックスを使用するようになりました。

追加

  • セカンドツールバーに対応しました。

  • メインメニューのツールバーに編集のためのセカンドツールバーを次のとおり追加しました:「テキストツール」「描画ツール」「添付ファイルとスタンプ」「フォームツール」「ページツール」
    これにより、注釈編集モードやフォーム編集モードに切り替えることなく、ドキュメントを編集できるようになりました。
    どのツールバーを有効にするかを制御するには、secondToolbarLayout プロパティを使用します。

    // 例:セカンドツールバーのレイアウトを指定します。
    viewer.secondToolbarLayout = { "text-tools": ['edit-text', 'edit-free-text'] };
    
  • 独自のセカンドツールバーを表示するための API を追加しました。

    // 例:キー「custom-toolbar-key」にて独自のセカンドツールバーを作成します。
    var React = viewer.getType("React");
    var toolbarControls = [React.createElement("label", { style: {color: "white"} }, "独自のツールバー"),
    React.createElement("button", { onClick: () => { alert("アクションが実行されました。"); }, title: "Action title" }, "アクション")];
    // 独自のセカンドツールバーを「custom-toolbar-key」として登録します。
    viewer.options.secondToolbar = {
     render: function(toolbarKey) {
       if(toolbarKey === "custom-toolbar-key")
         return toolbarControls;
       return null;
     }
    };
    // 独自のセカンドツールバーを表示します。
    viewer.showSecondToolbar("custom-toolbar-key");
    
  • タグ付き PDF の構造ツリーを表示する構造ツリーパネルを追加しました。

    // 構造ツリーパネルを追加するには、addStructureTreePanel メソッドを使用します。
    const viewer = new GcPdfViewer(selector);
    viewer.addStructureTreePanel();
    await viewer.open("sample.pdf");
    
    // 利用可能な構造ツリーデータを取得するには、structureTree プロパティを使用します。
    const viewer = new GcPdfViewer(selector);
    await viewer.open("sample.pdf");
    const structureTree = await viewer.structureTree;
    if(structureTree) {
     console.log(structureTree);
    }
    
  • PDF レイヤーの表示/非表示を切り替えることができる、レイヤーパネルを追加しました。

    // 例:
    viewer.addLayersPanel();
    
  • レイヤーの設定を行う optionalContentConfig プロパティを追加しました。

    // 例:ID が「13R」のレイヤー を非表示にします。
    const config = await viewer.optionalContentConfig;
    config.setVisibility("13R", false);
    viewer.repaint();
    
    // 例:利用可能なレイヤーに関する情報をコンソールに表示します。
    const config = await viewer.optionalContentConfig;
    console.table(config.getGroups());
    
  • サイドパネルを開く openPanel メソッドを追加しました。

    // 例:
    const layersPanelHandle = viewer.addLayersPanel();
    viewer.open("house-plan.pdf").then(()=> {
      viewer.openPanel(layersPanelHandle);
    });
    
  • サイドパネルを閉じる closePanel メソッドを追加しました。

    // 例:
    viewer.closePanel();
    
  • resetChanges メソッドを追加しました。すべての変更点を破棄し、ドキュメントを元の状態にリセットします。

    // 例:
    await viewer.resetChanges();
    
  • goToPage メソッドを追加しました。0から始まるインデックスによって指定されたページに移動します。

    //例:最初のページに移動します。
    viewer.goToPage(0);
    
  • setPageRotation(pageIndex, rotation) メソッドを追加しました。PDF の特定のページを回転させることができます。
    このメソッドの使用には SupportApi が必要です。また、回転の指定に有効な値は、0/90/180/270度です。

    // 例:1ページ目を180度回転します。
    await viewer.setPageRotation(0, 180);
    
  • getPageRotation(pageIndex) メソッドを追加しました。指定したページの回転値を取得します。

    // 例:1ページ目の回転(度)を取得します。
    var rotation = viewer.getPageRotation(0);
    
  • 新しいテーマとして Light テーマと Dark テーマを追加しました。

  • requireTheme オプションを追加しました。このオプションを使用して組み込みの CSS テーマを適用することで、テーマスタイルがページヘッドに直接挿入されます。
    なお、既存の組み込みテーマのみが指定可能で、それ以外が指定された場合はビューワの読み込みに失敗します。
    指定可能な組み込みテーマ次のとおりです:「viewer」「dark」「dark-yellow」「gc-blue」「light」「light-blue」
    また、このオプションはカスタムテーマを指定するために使用する theme オプションよりも優先されます。

    // 例:
    var viewer = new GcPdfViewer(selector, { 
         requireTheme: "light"
    });
    
  • onThemeChanged イベントを追加しました。ユーザがビューワのテーマを変更したときに発生します。

    // 例:
    var viewer = new GcPdfViewer(selector, { 
         requireTheme: localStorage.getItem('demo_theme') || 'viewer'
     });
     viewer.addDefaultPanels();
     viewer.onThemeChanged.register(function(args) {
       localStorage.setItem('demo_theme', args.theme);
     });
    
  • onInitialized オプションを追加しました。onInitialized ハンドラは、ビューワをインスタンス化した直後に呼び出します。

    // 例:
    var viewer = new GcPdfViewer("#root", { 
      onInitialized: (viewer)=> { 
        // ビューワの初期化コードをここに記述します。
      } 
    });
    
  • fieldsAppearance オプションを追加しました。フォームフィールドのレンダリング方法を指定します。
    このオプションは、フォームフィールドのレンダリングをカスタマイズするために使用します。 使用可能なレンダリングの外観タイプは以下のとおりです。

    • Custom:デフォルト値です。[Web]の外観ではサポートされていない背景色と枠線のスタイルを追加した外観を使用します。
    • Web:Web のフォームフィールドの標準的な外観を使用します。なお、OS/ブラウザに依存したスタイルで表示されます。 詳しくは https://developer.mozilla.org/en-US/docs/Web/CSS/appearance をご覧ください。
    • Predefined:PDF から定義済みの外観ストリームを取得して使用します。外観ストリームが利用できない場合は[Custom]の外観を使用します。
    // 例1:ラジオボタンとチェックボックスの外観に[Web]を設定します。
    var viewer = new GcPdfViewer("#root", { fieldsAppearance: { radioButton: "Web", checkBoxButton: "Web" } });
    
    // 例2:ラジオボタンの外観に[Predefined]を設定します。
    var viewer = new GcPdfViewer("#root", { fieldsAppearance: { radioButton: "Predefined" } });
    
  • GET メソッドを使用してフォームを送信できるようになりました。

    // GcPdf にて、GET メソッドを使用してフォームを送信する ActionSubmitForm を作成します。
    var actionSubmit = new ActionSubmitForm("/");
    actionSubmit.SubmitFormat = ActionSubmitForm.SubmitFormatType.HtmlForm;
    actionSubmit.HtmlFormFormat = ActionSubmitForm.HtmlFormFormatFlags.GetMethod;
    var btnSubmit = new PushButtonField();
    btnSubmit.Widget.Rect = new RectangleF(50, 100, 100, 50);
    btnSubmit.Widget.ButtonAppearance.Caption = "送信";
    btnSubmit.Widget.Page = page;
    btnSubmit.Widget.Events.Activate = actionSubmit;
    
  • リセットアクションに FieldNames/ExcludeSpecifiedFields/Next プロパティのサポートを追加しました。

  • enableXfa オプションを追加しました。XFA(XML Forms Architecture)フォームがある場合、レンダリングするかどうかを指定します。デフォルトは true です。

    // 例:XFA フォームのレンダリングを無効にします。
    var viewer = new GcPdfViewer(selector, { enableXfa: false });
    
  • XFA フォームのテキストコンテンツを選択/コピーする機能を追加しました。

  • maxCanvasPixels オプションを追加しました。対応する最大の canvas サイズをピクセル単位(幅×高さ)で指定します。未指定または-1を指定した場合は無制限となります。 canvas のスケーリングが maxCanvasPixels を超える場合、canvas にページを再描画する代わりに、CSS のスケーリングが使用されます。

  • エディタにて最後に使用した値を記憶できるようになりました。
    editorDefaults オプションに新しく次の設定を追加しました:rememberLastValues/lastValueKeys
    rememberLastValues に true または undefined を設定した場合、最後に使用したプロパティ値を新しい注釈のデフォルト値として使用します。 lastValueKeys は、どのプロパティを記憶するかを指定します。

  // lastValueKeys のデフォルト値:
  ["appearanceColor", "borderStyle", "color", "interiorColor", "backgroundColor", "borderColor", "opacity", "textAlignment", "printableFlag", "open",
  "lineStart", "lineEnd", "markBorderColor", "markFillColor", "overlayFillColor", "overlayText", "overlayTextJustification", "newWindow", "calloutLineEnd", "fontSize",
  "fontName", "name", "readOnly", "required"]
  // 例:最後に使用した値を記憶しないようにします。
  var viewer = new GcPdfViewer("#root", { editorDefaults: { rememberLastValues: false } });
  // 例:borderStyle プロパティだけ記憶します。
  var viewer = new GcPdfViewer("#root", { editorDefaults: { rememberLastValues: true, lastValueKeys: ["borderStyle"] } });
  • [Android] ピンチ操作によるズームに対応しました。

変更

  • PDF.js ライブラリを v2.0.943 から v2.10.377 に更新しました。更新内容は PDF.js のリリースノートをご参照ください。
  • goToPageNumber メソッドは非推奨になりました。代わりに goToPage メソッドまたは pageIndex プロパティを使用してください。
  • ラジオボタンとチェックボックスは PDF にて定義された外観をデフォルトで使用しなくなりました。 以下のとおり fieldsAppearance オプションを使用すると、以前の動作に戻すことができます。
  var viewer = new GcPdfViewer("#root", { fieldsAppearance: { radioButton: "Predefined", checkBoxButton: "Predefined" } });
  • SupportApi の情報を取得する ping メソッドは廃止となり使用できなくなりました。代わりに serverVersion メソッドを使用してください。
  • SubmitForm/ResetForm プロパティは submitForm/resetForm に名称が変わりました。

不具合の修正

  • [4409748657935] [PDFビューワ] iOS/iPadOS/MacOSのSafariにて拡大・縮小を繰り返すと、PDFのページが表示されなくなる
詳細なリリースノートについては、 CHANGELOG-JP.​md をご参照ください。

製品デモ

  • PDFビューワの製品デモ では、SupportAPI を使用する編集機能を含め、 PDFビューワの様々な機能を紹介しています。 このデモでは、クライアント側のコードを変更し、どのように反映されるか確認することもできます。
  • DioDocs for PDFの製品デモ 内のすべてのデモでは、PDFビューワを使用してPDFを表示しています。

インストール

npm install @grapecity/gcpdfviewer

製品ヘルプ

製品ヘルプはこちらからご覧いただけます。

ライセンス

GrapeCity PDF ビューワのご利用にはライセンスが必要となります。詳しくはWebサイトのライセンス手続きページをご覧ください。

製品情報

GrapeCity PDF ビューワは、DioDocs for PDF の一部として提供しております。製品に関する詳細な情報については、Webサイトの製品情報ページをご参照ください。

PDFビューワの詳細な使用方法

HTMLページへのPDFビューワの追加

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <!--コンテンツの拡大縮小を制限して、モバイルデバイスでビューワが正しくズームできるようにします。-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="theme-color" content="#000000" />
    <title>GrapeCity PDF ビューワ</title>
    <script type="text/javascript" src="lib/node_modules/@grapecity/gcpdfviewer/gcpdfviewer.js"></script>
    <script>
        function loadPdfViewer(selector) {
            var viewer = new GcPdfViewer(selector,
                {
                    /* ここでオプションを指定します */
                    renderInteractiveForms: true
                });
            viewer.addDefaultPanels();
            // 必要に応じてPDFを開きます(サーバーから実行時にのみ機能)
            viewer.open('HelloWorld.pdf');
            // デフォルトのビューワのツールバーを変更します
            viewer.toolbarLayout.viewer.default = ['$navigation', '$split', 'text-selection', 'pan', '$zoom', '$fullscreen',
                'save', 'print', 'rotate', 'view-mode', 'doc-title'];
            viewer.applyToolbarLayout();
        }
    </script>
</head>
<body onload="loadPdfViewer('#root')">
    <div id="root"></div>
</body>
</html>

PDFビューワへのライセンスの適用

GcPdfViewer のインスタンスを作成して初期化する前に、PDFビューワのライセンスキーを GcPdfViewer.License プロパティに設定します。 なお、これは jsファイルを参照するコードの前に記述する必要があります。

  // ご自身のライセンスを追加してください
  GcPdfViewer.LicenseKey = 'xxx';
  // 適宜コードを追加してください
  const viewer = new GcPdfViewer('#root', { file: 'helloworld.pdf' });
  viewer.addDefaultPanels();

PDFビューワの検索オプション

PDFビューワには、以下のようなテキストの検索オプションが用意されていますが、英語のみの対応となっており、日本語は正しく検索できない場合があります。

  • 大/小文字を区別
  • 単語単位で検索
  • 単語の先頭を検索
  • 単語の末尾を検索
  • ワイルドカード
  • 近接

上記検索オプションを非表示にしたい場合は、ページの<head>部分に以下のとおりCSSスタイルを追加してください。

<style>
    .gc-viewer .search .search__query-params > label:nth-child(1),
    .gc-viewer .search .search__query-params > label:nth-child(2),
    .gc-viewer .search .search__query-params > label:nth-child(3),
    .gc-viewer .search .search__query-params > label:nth-child(4),
    .gc-viewer .search .search__query-params > label:nth-child(5),
    .gc-viewer .search .search__query-params > label:nth-child(6) {
        display: none;
    }
</style>

SupportAPI

SupportAPI は、DioDocs for PDFとともにC#のソースコードにて提供されるサーバーサイドのライブラリです。完全なソースコードは、PDFビューワの製品デモ からダウンロードできるすべてのPDFビューワのサンプルに含まれています。 このソースは、ASP.​NET CoreまたはWebFormsアプリケーションで使用するためにビルドすることができます。 (WebForms の場合は、ソースの #if WEB_FORMS をご参照ください。) PDFビューワがSupportAPIに接続されると、編集機能が有効になります。クライアント上で行われた編集は蓄積されており、ユーザーが「保存」をクリックすると、ドキュメントと編集内容がサーバーに送信され、編集が適用されて、変更されたPDFがクライアントに返送されます。

ASP.​NET Coreアプリ(ASP.​NET Core 3.0以上が必要)でSupportAPIを提供するサーバを設定するには:

  • PDFビューワの製品デモ から任意のサンプルをダウンロードしてください (例:PDFの編集)。
  • ダウンロードした.zipをディレクトリに解凍します。
  • そのディレクトリには「WebApi.zip」が格納されており、完全なSupportAPIのC#ソース(WebApi.zip/WebApi/SupportApi)、 ASP.​NET Core(WebApi.zip/WebApi/AspNetCore.sln)及びWebForms(WebApi.zip/WebApi/WebForms.sln)のサンプルプロジェクトが含まれています。
  • サンプルのディレクトリにあるrun.cmdバッチファイルを実行すると、SupportApiのファイルが解凍され、サービスがビルドされて起動されるとともに、 サンプルもビルドされて実行され、サンプルのURL (http://localhost:3003) がデフォルトのブラウザで開きます。
  • ディレクトリ「WebApi.zip/WebApi/SupportApi」とその中にあるものは、SupportAPIライブラリです。お客様のプロジェクトでそのままお使いいただけます。
  • 「WebApi.zip/WebApi/SupportApi/Controllers/GcPdfViewerController.cs」には、APIのエントリーポイントが含まれています。どのような操作が可能か確認してみてください。
  • 詳細については、ダウンロードしたビューワのサンプルに含まれているreadme.​mdをご覧ください。

なお、SupportAPIを使用するには、有効なDioDocs for PDFライセンスが必要です。 ライセンスは、GcPdfDocumentのSetLicenseKey静的メソッドにて設定します。以下の例は、「SupportApi/Controllers/GcPdfViewerController.cs」にコンストラクタを追加し、その中でDioDocs for PDFライセンスをSupportAPIに適用する方法を示しています。

public GcPdfViewerController()
    {
        GcPdfDocument.SetLicenseKey("ライセンスキー");
    }

キーボードのショートカット

表示モード

  • Ctrl + - 拡大
  • Ctrl - - 縮小
  • Ctrl 0 - 100%に拡大
  • Ctrl 9 - ページ幅に合わせて拡大
  • Ctrl A - すべて選択
  • R - ドキュメントを右回りに回転
  • Shift R - ドキュメントを左回りに回転
  • H - 手のひらツールを有効化
  • S - 選択ツールを有効化
  • Ctrl O - PDFファイルを開く
  • Ctrl F - テキスト検索
  • Ctrl P - 印刷
  • Home - 行頭に移動
  • Ctrl Home - ドキュメントの先頭に移動
  • Shift Home - 行頭まで選択
  • Shift Ctrl Home - ドキュメントの先頭まで選択
  • End - 行末に移動
  • Ctrl End - ドキュメントの末尾に移動
  • Shift End - 行末まで選択
  • Shift Ctrl End - ドキュメントの末尾まで選択
  • Left - 左に移動
  • Shift Left - 左を選択
  • Alt Left - 前の履歴に戻る
  • Right - 右に移動
  • Shift Right - 右を選択
  • Alt Right - 次の履歴に進む
  • Up - 上に移動
  • Shift Up - 上まで選択
  • Down - 下に移動
  • Shift Down - 下まで選択
  • PgUp - 前のページに移動
  • PgDown - 次のページに移動
  • Shift PgUp - 前のページまで選択
  • Shift PgDown - 次のページまで選択

編集モード

  • Delete - 選択した注釈/フィールドを削除
  • Esc - 注釈/フィールドの選択を解除
  • Ctrl Z - 元に戻す
  • Ctrl Y - やり直す
  • Ctrl Shift Z - やり直す

ツールバーの項目

PDFビューワのデフォルトのツールバーレイアウトは以下のとおりです。(' で始まる項目は、ビューワの標準として備わっているものであり、それ以外の項目はPDFビューワ固有のものになります。)

['open', '$navigation', '$split', 'text-selection', 'pan', '$zoom', '$fullscreen', 'rotate', 'view-mode', 'theme-change', 'download', 'print', 'save', 'hide-annotations', 'doc-title', 'doc-properties', 'about']

PDFビューワ固有のツールバー項目は以下のとおりです。

'text-selection', 'pan', 'open', 'save', 'download', 'print', 'rotate', 'theme-change', 'doc-title', 'view-mode', 'single-page', 'continuous-view'

ビューワの標準のツールバー項目は以下のとおりです。

'$navigation' '$refresh', '$history', '$mousemode', '$zoom', '$fullscreen', '$split'

以下のように、getDefaultToolbarItems() メソッドを使用することで、デフォルトのツールバー項目を取得することができます。

const toolbar: Toolbar = viewer.toolbar;
let buttons = toolbar.getDefaultToolbarItems();
buttons = buttons.filter(b => b !== '$refresh');

ツールバー項目をカスタマイズするには、以下のように toolbarLayout プロパティと applyToolbarLayout() メソッドを使用します。

viewer.toolbarLayout.viewer = {
  default: ["$navigation", 'open', '$split', 'doc-title'],
  fullscreen: ['$fullscreen', '$navigation'],
  mobile: ["$navigation", 'doc-title']
};
viewer.toolbarLayout.annotationEditor = {
  default: ['edit-select', 'save', '$split', 'edit-text'],
  fullscreen: ['$fullscreen', 'edit-select', 'save', '$split', 'edit-text'],
  mobile: ['$navigation']
};
viewer.toolbarLayout.formEditor = {
  default: ['edit-select-field', 'save', '$split', 'edit-widget-tx-field', 'edit-widget-tx-password'],
  fullscreen: ['$fullscreen', 'edit-select-field', 'save', '$split', 'edit-widget-tx-field', 'edit-widget-tx-password'],
  mobile: ['$navigation']
};
viewer.applyToolbarLayout();

以下のように、独自のカスタムツールバーボタンを作成することもできます。

const toolbar: Toolbar = viewer.toolbar;
toolbar.addItem({
  key: 'my-custom-button',
  iconCssClass: 'mdi mdi-bike',
  title: 'カスタムボタン',
  enabled: false,
  action: () => {
    alert("カスタムツールバーボタンがクリックされました");
  },
  onUpdate: (args) => ({ enabled: viewer.hasDocument }),
});
viewer.toolbarLayout.viewer.default =  ['$navigation', 'my-custom-button'];
viewer.applyToolbarLayout();

Preact でのPDFビューワの使用

PDFビューワのスクリプトへの参照を追加します。

<body>
  <script type="text/javascript" src="/lib/gcpdfviewer/gcpdfviewer.js"></script>
  ...

アプリのテンプレートに以下のようにプレースホルダを追加します。

<section id="pdf"></section>

PDFビューワをレンダリングします。

let viewer = new GcPdfViewer('section#pdf');
viewer.addDefaultPanels();

The End.