add-pdf-viewer — скилл для Claude Code: что делает и как установить
Скилл add-pdf-viewer настраивает обёртку для встроенного просмотра PDF по ссылкам HTTPS и локальным путям file:// в мобильных приложениях Power Platform.
MIT ★ 1 167 обновлён 2026-10-29
/plugin marketplace add microsoft/power-platform-skills
/plugin install mobile-app@power-platform-skillsЧто делает add-pdf-viewer
Скилл работает как внутренний обработчик команды /add-native в Claude Code. Сначала он проверяет структуру проекта на наличие файлов app.config.js, power.config.json, package.json и папки src. Если проект не инициализирован, выполнение сразу останавливается.
Далее агент валидирует установленную библиотеку @microsoft/power-apps-native-pdf-viewer. Пакет версии 0.2.9 или выше уже обязан присутствовать в сборке: скилл намеренно не выполняет установку через npm и не меняет конфигурацию нативных платформ. После проверок создаётся или обновляется файл src/native/pdfViewer.ts.
Готовая TypeScript-обёртка отсекает неподдерживаемые схемы http://, blob: и content://, возвращая типизированный результат без выброса исключений. Без предварительной сборки нативного модуля с версией 0.2.9+ вызов завершится ошибкой NATIVE_MODULE_MISSING.
Какие задачи решает
- сгенерировать TypeScript-обёртку для нативного компонента просмотра PDF
- проверить совместимость установленной версии библиотеки с протоколом file://
- валидировать входящие URL и отсечь протоколы вроде blob и content
- обработать нативные события печати, экспорта и закрытия документа
Примеры запросов агенту
- /add-native pdf-viewer
- /add-native pdf-control
- /add-native @microsoft/power-apps-native-pdf-viewer
Как установить add-pdf-viewer
1Через маркетплейс плагинов
/plugin marketplace add microsoft/power-platform-skills/plugin install mobile-app@power-platform-skillsКоманда ставит плагин mobile-app целиком, со всеми его скиллами
2Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-pdf-viewer -a claude-code3Вручную: положить файлы
~/.claude/skills/add-pdf-viewer/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/add-pdf-viewer/
1Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-pdf-viewer -a codex2Вручную: положить файлы
.agents/skills/add-pdf-viewer/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-pdf-viewer -a cursor2Вручную: положить файлы
.cursor/skills/add-pdf-viewer/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install microsoft/power-platform-skills plugins/mobile-apps/skills/add-native/add-pdf-viewer2Вручную: положить файлы
.github/skills/add-pdf-viewer/SKILL.md1Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-pdf-viewer -a gemini-cli2Командой платформы
gemini skills install https://github.com/microsoft/power-platform-skills --path plugins/mobile-apps/skills/add-native/add-pdf-viewerВручную: положить файлы
.devin/skills/add-pdf-viewer/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Claude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы об add-pdf-viewer
Как установить add-pdf-viewer в Claude Code?
Выполните в консоли /plugin marketplace add microsoft/power-platform-skills, затем запустите /plugin install mobile-app@power-platform-skills.
Что делает скилл add-pdf-viewer?
Он проверяет готовность мобильного проекта и генерирует модуль src/native/pdfViewer.ts для открытия файлов через @microsoft/power-apps-native-pdf-viewer.
Какие протоколы поддерживает сгенерированная обёртка?
Код принимает адреса https:// и локальные пути file://. Небезопасный http://, схемы blob: и content:// отклоняются валидатором.
Исходный текст
SKILL.md · MIT
---
name: add-pdf-viewer
description: Internal implementation skill invoked by /add-native for native PDF control workflows. Handles HTTPS and file URI PDF viewing with @microsoft/power-apps-native-pdf-viewer 0.2.9+.
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 package is already present
```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-pdf-viewer'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template/app must already ship this native extension. This skill will not install it or edit native config.'); process.exit(1); } let v; try { v=require('./node_modules/' + m + '/package.json').version; } catch { console.error('MISSING_INSTALL: cannot verify the installed ' + m + ' version. Run the project package install first.'); process.exit(1); } const [major,minor,patch]=v.split('.').map(Number); if (!(major > 0 || minor > 2 || (minor === 2 && patch >= 9))) { console.error('UNSUPPORTED_VERSION: ' + m + ' ' + v + ' does not support file:// URIs. Version 0.2.9+ is required.'); process.exit(1); } console.log('OK: native PDF viewer ' + v + ' supports https:// and file://');"
```
If the check fails, STOP. Do not run `npm install`, `npx expo install`, `pod install`, or edit `app.config.js`. Version 0.2.9+ must already be part of the app's native build.
### 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 { NativePdfViewer } from '@microsoft/power-apps-native-pdf-viewer';
export type PdfViewerResult =
| { ok: true; action?: 'shared' | 'printed' | 'dismissed' }
| { ok: false; reason: 'INVALID_URL' | 'NATIVE_MODULE_MISSING' | 'VIEWER_FAILED'; message?: string };
export async function openHttpsPdf(
url: string,
options?: { title?: string; maxFileSizeMb?: number; cacheEnabled?: boolean },
): Promise<PdfViewerResult> {
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.' };
}
if (!NativePdfViewer?.openPdf) {
return { ok: false, reason: 'NATIVE_MODULE_MISSING', message: 'Native PDF viewer module is not available in this build.' };
}
try {
const response = await NativePdfViewer.openPdf(url, {
maxFileSizeMb: 50,
cacheEnabled: true,
...options,
});
if (response.status === 'ok') {
return { ok: true, action: response.result?.action };
}
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 `@microsoft/power-apps-native-pdf-viewer` only for this native PDF viewing use case.
- 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.
### 6. Native rebuild note
This skill does not install native code. If the package was just added outside the skill, the app needs a native rebuild outside this workflow. If the package was already in the build, Metro hot reload is enough for wrapper edits.
### 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
Package present : @microsoft/power-apps-native-pdf-viewer
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 added — @microsoft/power-apps-native-pdf-viewer (<ISO date>)
```
© Microsoft · MIT · microsoft/power-platform-skills