Skip to content

microsoft/power-platform-skills / plugins/mobile-apps/skills/add-native/add-pdf-viewer

add-pdf-viewer

Verified

Internal implementation skill invoked by /add-native for native PDF viewing through release-matched controls or legacy PDF leaf APIs.

FileKindSize
SKILL.mdskill md9.0 KB
---
name: add-pdf-viewer
description: Internal implementation skill invoked by /add-native for native PDF viewing through release-matched controls or legacy PDF leaf APIs.
user-invocable: false
disable-model-invocation: true
allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion
model: sonnet
---

**📋 Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.

**Working directory:** before any project read or command, execute
[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
file tool to it, even when this helper starts from another directory.

# Add PDF Viewer

**Internal helper.** Users should invoke `/add-native pdf-viewer`, `/add-native pdf-control`, or `/add-native @microsoft/power-apps-native-pdf-viewer`; `/add-native` routes here after resolving the capability.

Generate or verify the native PDF viewer wrapper and show how to call its **native React Native API**. Version 0.2.9 and later support HTTPS PDF URLs and local `file://` URIs. Do not use the HostingSDK / PCF path from the package README; that is for a different use case.

## Steps

### 1. Verify app

```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
```

If this fails, tell the user to run `/create-mobile-app` first and STOP.

### 2. Verify the app-matched release and import path

```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>' --local-development
```

Read [release lifecycle](../../../shared/references/mobile-release-lifecycle.md)
and [native controls](../references/native-controls.md), including the shared
local-development policy. Do not install packages, run local native builds,
or edit native config. Apply the native-controls import-selection rules to the
strict/local context; file URI support requires the PDF 0.2.9+ contract in the binary.

The example below uses `@microsoft/power-apps-native-controls/pdf`. When the
import-selection rules select the legacy leaf, replace only the literal import
with `@microsoft/power-apps-native-pdf-viewer`. Do not import the root
aggregate or emit a runtime fallback between packages.

### 2a. Reconcile requested artifacts

Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
Steps 1–3 for the PDF viewer row before any writes or reuse. Inherit the current
approval/mode from `/add-native`; do not repeat a valid scoped approval.
Inspect `src/native/pdfViewer.ts` for `openHttpsPdf`, `PdfViewerResult`, requested
options/actions, and the actual HTTPS/local-file behavior against installed
version 0.2.9+. An HTTPS-only implementation cannot satisfy a requested local
`file://` preview. Check invalid URI and missing-native-module paths, not just
exports; an incompatible artifact outside approval returns `NEEDS_CONTEXT` to
the owner, or asks standalone.

### 3. Write or verify `src/native/pdfViewer.ts`

Apply Step 2a's decision for `src/native/pdfViewer.ts`: create when requested and
missing, reuse unchanged only if compatible, or make only the approved scoped
update. Preserve custom code, exports, and callers; do not overwrite from the example.

The wrapper MUST:

- Accept `https://` URLs and `file://` URIs.
- Reject `content://`, `blob:`, `http://`, empty, and malformed URLs before calling native code.
- Return a discriminated union and never throw.
- Return `NATIVE_MODULE_MISSING` when the extension is installed in JS but unavailable in the native build.
- Surface viewer action results (`shared`, `printed`, `dismissed`) when available.
- Return `VIEWER_FAILED` for native errors not covered by validation/module checks.

```ts
// src/native/pdfViewer.ts
import { Platform } from 'react-native';

export type PdfViewerResult =
  | { ok: true; action?: 'shared' | 'printed' | 'dismissed' }
  | { ok: false; reason: 'UNSUPPORTED_PLATFORM' | 'INVALID_URL' | 'NATIVE_MODULE_MISSING' | 'VIEWER_FAILED'; message?: string };

export async function openHttpsPdf(
  url: string,
  options?: { title?: string; maxFileSizeMb?: number; cacheEnabled?: boolean },
): Promise<PdfViewerResult> {
  if (Platform.OS !== 'ios' && Platform.OS !== 'android') {
    return { ok: false, reason: 'UNSUPPORTED_PLATFORM' };
  }

  let parsed: URL;
  try {
    parsed = new URL(url);
  } catch {
    return { ok: false, reason: 'INVALID_URL', message: 'PDF location must be a valid https:// URL or file:// URI.' };
  }

  const isHttpsUrl = parsed.protocol === 'https:';
  const isFileUri = parsed.protocol === 'file:' && url.startsWith('file://') && parsed.pathname !== '/';
  if (!isHttpsUrl && !isFileUri) {
    return { ok: false, reason: 'INVALID_URL', message: 'Native PDF viewer supports https:// and file:// inputs only.' };
  }

  try {
    const { NativePdfViewer } = await import('@microsoft/power-apps-native-controls/pdf');
    if (!NativePdfViewer?.openPdf) {
      return { ok: false, reason: 'NATIVE_MODULE_MISSING' };
    }
    const response = await NativePdfViewer.openPdf(url, {
      maxFileSizeMb: 50,
      cacheEnabled: true,
      ...options,
    });

    if (response.status === 'ok') {
      return { ok: true, action: response.result?.action };
    }

    if (response.error === 'NATIVE_MODULE_MISSING') {
      return { ok: false, reason: 'NATIVE_MODULE_MISSING' };
    }
    return { ok: false, reason: 'VIEWER_FAILED', message: response.message ?? response.error };
  } catch (error: any) {
    return { ok: false, reason: 'VIEWER_FAILED', message: error?.message ?? String(error) };
  }
}
```

### 4. Use the wrapper

Integration guidance for the owner; do not edit screens in this helper.

Screens import the wrapper, not the native package directly:

```ts
import { openHttpsPdf } from '@/native/pdfViewer';

const response = await openHttpsPdf('https://example.com/report.pdf', {
  title: "Inspection report",
});

if (response.ok) {
  switch (response.action) {
    case "shared":
      // User completed native Share.
      break;
    case "printed":
      // User completed native Print.
      break;
    case "dismissed":
      // User closed the viewer.
      break;
  }
} else {
  console.warn("Failed to open PDF:", response.reason, response.message);
}
```

Notes:
- URLs must use `https://` or a non-empty `file://` URI. `content://`, `blob:`, and `http://` are not supported by this skill.
- Use the selected `/pdf` or verified legacy PDF import only for native PDF viewing.
- Use `expo-document-picker` for picking/importing/uploading a local PDF or document.
- Use `/add-native pdf-report` for generated local PDFs. That helper requires `expo-print` and adds sharing behavior only when `expo-sharing` is already present.
- Generated local PDFs from `expo-print` may be opened by native PDF viewer 0.2.9+ as `file://` URIs.
- Share and Print are built into the native viewer; there are no separate JS share/print calls.
- The wrapper returns `{ ok: true } | { ok: false }`; handle every non-ok reason in UI.

### 5. Type-check

```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```

Fix only in-scope helper errors, then execute the shared compatibility contract's
Step 4. Recheck requested inputs/options/actions, invalid URI rejection, missing
native module, and viewer failures. Type-check success alone is insufficient;
do not fix screen/generated files.

This does not constitute native device validation.

### 6. Native rebuild note

This skill does not install native code or run local native builds. An
out-of-band package addition is a compatibility block, not proof of support.
Use a separately approved verified-release migration; Metro updates only JS.

### 7. Do not use HostingSDK / PCF

Do not import or register:

```ts
import NativePdfViewerExtension from "@microsoft/power-apps-native-pdf-viewer";
```

Do not wire Companion PCF or `NativePdfViewerExtension`. In Power Apps native code apps, use the native React Native API above.

### 8. Summary

Return the shared compatibility result and actual created/updated/reused paths
before this summary. Update memory-bank only after success, and leave final
updates to the owner when orchestrated.

Tell the user:

```text
PDF viewer added
Release / package : <resolved release and selected package/version>
Wrapper           : src/native/pdfViewer.ts
URL support       : HTTPS and file:// (0.2.9+)
Type-check        : PASS
Native rebuild    : not performed by this skill
Usage             : openHttpsPdf(...)
HostingSDK / PCF  : not used
```

Update `memory-bank.md` under `Controls`:

```text
- PDF viewer wrapper added — <resolved release + selected import/version> (<ISO date>); native device validation: <performed / not performed>
```
canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall