pdf-to-markdown-mcp 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ name: Publish to npm
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+ inputs:
8
+ version:
9
+ description: 'Version to publish'
10
+ required: true
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ publish:
17
+ runs-on: ubuntu-latest
18
+ permissions:
19
+ contents: read
20
+ id-token: write
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+
24
+ - uses: actions/setup-node@v4
25
+ with:
26
+ node-version: '18'
27
+ registry-url: 'https://registry.npmjs.org'
28
+
29
+ - name: Install dependencies
30
+ run: npm ci
31
+
32
+ - name: Run security audit
33
+ run: npm audit --omit=dev --audit-level=moderate
34
+
35
+ - name: Build
36
+ run: npm run build
37
+
38
+ - name: Publish to npm
39
+ run: npm publish
40
+ env:
41
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -0,0 +1,19 @@
1
+ {
2
+ "version": "0.2.0",
3
+ "configurations": [
4
+ {
5
+ "type": "node",
6
+ "request": "attach",
7
+ "name": "Attach to pdf-to-markdown MCP Server (Agent Mode)",
8
+ "port": 9329,
9
+ "restart": true,
10
+ "sourceMaps": true,
11
+ "outFiles": [
12
+ "${workspaceFolder}/dist/**/*.js"
13
+ ],
14
+ "skipFiles": [
15
+ "<node_internals>/**"
16
+ ]
17
+ }
18
+ ]
19
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "servers": {
3
+ "pdf-to-markdown-mcp": {
4
+ "type": "stdio",
5
+ "command": "node",
6
+ "args": [
7
+ "--inspect=9329",
8
+ "./dist/index.js"
9
+ ],
10
+ "env": {
11
+ "QWEN_API_URL": "QWEN_API_URL",
12
+ "QWEN_API_KEY": "QWEN_API_KEY"
13
+ }
14
+ }
15
+ }
16
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "chat.instructionsFilesLocations": {
3
+ ".github/instructions": true,
4
+ "C:\\Users\\YXZHK\\source\\explore\\awesome-copilot\\instructions\\markdown.instructions.md": true,
5
+ "C:\\Users\\YXZHK\\source\\explore\\awesome-copilot\\instructions\\security-and-owasp.instructions.md": true,
6
+ "C:\\Users\\YXZHK\\source\\explore\\awesome-copilot\\instructions\\self-explanatory-code-commenting.instructions.md": true,
7
+ "C:\\Users\\YXZHK\\source\\explore\\awesome-copilot\\instructions\\typescript-mcp-server.instructions.md": true,
8
+ "C:\\Users\\YXZHK\\source\\explore\\awesome-copilot\\instructions\\typescript-5-es2022.instructions.md": true,
9
+ },
10
+ }
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # PDF to Markdown MCP Server
2
+
3
+ A Model Context Protocol (MCP) server that converts PDF pages to markdown format using the Qwen VL vision model API.
4
+
5
+ ## Features
6
+
7
+ - **PDF Page Conversion**: Convert any page from a PDF document to markdown format
8
+ - **AI-Powered Extraction**: Uses Qwen VL model for accurate text and structure extraction
9
+ - **High-Resolution Rendering**: Converts PDF pages to 2x scale images for better accuracy
10
+ - **Modern MCP API**: Uses the latest `McpServer` API for clean tool registration
11
+ - **Type-Safe**: Full TypeScript support with Zod schema validation
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install
17
+ npm run build
18
+ ```
19
+
20
+ ## Configuration
21
+
22
+ The server requires two environment variables:
23
+
24
+ - `QWEN_API_URL`: The endpoint URL for the Qwen VL API (e.g., `https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions`)
25
+ - `QWEN_API_KEY`: Your API key for authentication
26
+
27
+ By default, the server uses the `qwen-vl-max` model.
28
+
29
+ ### MCP Settings Configuration
30
+
31
+ Add this to your MCP client configuration (e.g., Claude Desktop config):
32
+
33
+ ```json
34
+ {
35
+ "mcpServers": {
36
+ "pdf-to-markdown": {
37
+ "command": "node",
38
+ "args": ["/path/to/PDFmdMCP/dist/index.js"],
39
+ "env": {
40
+ "QWEN_API_URL": "https://your-qwen-api-endpoint.com/v1/chat/completions",
41
+ "QWEN_API_KEY": "your-api-key-here"
42
+ }
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ *Note: Replace `/path/to/PDFmdMCP/dist/index.js` with the actual absolute path to the built `index.js` file on your system.*
49
+
50
+ ## Available Tools
51
+
52
+ ### convert_pdf_page_to_markdown
53
+
54
+ Converts a specific page from a PDF file to markdown format using AI vision analysis.
55
+
56
+ **Parameters:**
57
+ - `pdf_path` (string, required): Absolute path to the PDF file. Must exist and be readable.
58
+ - `page_number` (number, required): Page number to convert (1-indexed). Must be a positive integer between 1 and total pages.
59
+
60
+ **Returns:**
61
+ - Markdown-formatted text extracted from the PDF page
62
+
63
+ **Example:**
64
+ ```
65
+ Convert page 3 of /path/to/document.pdf to markdown
66
+ ```
67
+
68
+ ## How It Works
69
+
70
+ 1. **File Validation**: Verifies the PDF file exists and is accessible
71
+ 2. **PDF Processing**: Extracts the requested page using PDF.js library
72
+ 3. **Image Rendering**: Renders the PDF page as a PNG image at 2x scale for clarity
73
+ 4. **AI Analysis**: Sends the base64-encoded image to Qwen VL API
74
+ 5. **Markdown Extraction**: The vision model extracts text, tables, and structure
75
+ 6. **Result Return**: Returns formatted markdown to the client
76
+
77
+ ## Architecture
78
+
79
+ - **TypeScript 5.x**: Modern TypeScript targeting ES2022
80
+ - **MCP SDK**: Official `@modelcontextprotocol/sdk` with McpServer API
81
+ - **Zod Validation**: Type-safe schema validation for inputs
82
+ - **PDF.js**: Mozilla's robust PDF parsing library
83
+ - **Node Canvas**: Image rendering for PDF to PNG conversion
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ # Install dependencies
89
+ npm install
90
+
91
+ # Build the project
92
+ npm run build
93
+
94
+ # Watch mode for development
95
+ npm run dev
96
+
97
+ # Run tests
98
+ npm test
99
+ ```
100
+
101
+ ## System Dependencies
102
+
103
+ This project uses `node-canvas`, which may require additional system libraries for pdf rendering:
104
+
105
+ - **Windows**: Should work out of the box with prebuilt binaries.
106
+ - **macOS**: `brew install pkg-config cairo pango libpng jpeg giflib librsvg`
107
+ - **Linux (Ubuntu/Debian)**: `sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev`
108
+
109
+ ## Error Handling
110
+
111
+ The server provides detailed error messages for:
112
+ - Missing or invalid PDF files (`PDF file not found`)
113
+ - Invalid page numbers (outside document range)
114
+ - Invalid input parameters (non-integer page numbers, empty paths)
115
+ - API failures (connection errors, authentication, rate limits)
116
+ - Malformed API responses
117
+
118
+ All errors are returned as error content items with the `isError` flag set to true.
119
+
120
+ ## Security
121
+
122
+ - Environment variable based API key management (no hardcoded secrets)
123
+ - File path validation before processing
124
+ - Input sanitization for page numbers and file paths
125
+ - Error messages don't expose sensitive details
126
+
127
+
128
+ ## Requirements
129
+
130
+ - Node.js 18+
131
+ - Access to Qwen VL API endpoint
132
+ - Valid API key
133
+
134
+ ## License
135
+
136
+ MIT
137
+
138
+ ## Troubleshooting
139
+
140
+ **"PDF file not found"**: Ensure the path is absolute and the file exists
141
+
142
+ **"Invalid page number"**: Check that the page number is between 1 and the total pages in the PDF
143
+
144
+ **"Missing required environment variables"**: Verify `QWEN_API_URL` and `QWEN_API_KEY` are set in your MCP configuration
145
+
146
+ **"Qwen API request failed"**: Check your API key validity and endpoint URL
147
+
148
+ **Canvas context incompatibilities**: With `pdfjs-dist` v4/v5, several users report render-time failures in Node when using `node-canvas`, even with the "legacy" build. The error typically happens inside `CanvasGraphics.paintInlineImageXObject` / `paintImageXObject`. Pinning to `pdfjs-dist@4.8.69` has been confirmed as a temporary workaround and is used in this project.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import * as fs from "node:fs/promises";
5
+ import { z } from "zod";
6
+ import { convertPdfPageToImage } from "./pdfConverter.js";
7
+ /**
8
+ * Call Qwen VL API to convert image to markdown
9
+ */
10
+ async function convertImageToMarkdown(imageBuffer, apiUrl, apiKey) {
11
+ const base64Image = imageBuffer.toString("base64");
12
+ const requestBody = {
13
+ model: "qwen-vl-max",
14
+ input: {
15
+ messages: [
16
+ {
17
+ role: "user",
18
+ content: [
19
+ {
20
+ image: `data:image/png;base64,${base64Image}`,
21
+ },
22
+ {
23
+ text: "Please convert this image to markdown format. Extract all text, tables, and structure accurately.",
24
+ },
25
+ ],
26
+ },
27
+ ],
28
+ },
29
+ };
30
+ const response = await fetch(apiUrl, {
31
+ method: "POST",
32
+ headers: {
33
+ "Content-Type": "application/json",
34
+ Authorization: `Bearer ${apiKey}`,
35
+ },
36
+ body: JSON.stringify(requestBody),
37
+ });
38
+ if (!response.ok) {
39
+ const errorText = await response.text();
40
+ throw new Error(`Qwen API request failed: ${response.status} ${response.statusText} - ${errorText}`);
41
+ }
42
+ const result = (await response.json());
43
+ if (result.output?.text) {
44
+ return result.output.text;
45
+ }
46
+ throw new Error(`Unexpected API response format: ${JSON.stringify(result)}`);
47
+ }
48
+ /**
49
+ * Main server setup
50
+ */
51
+ async function main() {
52
+ const apiUrl = process.env.QWEN_API_URL;
53
+ const apiKey = process.env.QWEN_API_KEY;
54
+ if (!apiUrl || !apiKey) {
55
+ throw new Error("Missing required environment variables: QWEN_API_URL and QWEN_API_KEY must be set");
56
+ }
57
+ const server = new McpServer({
58
+ name: "pdf-to-markdown-mcp",
59
+ version: "1.0.0",
60
+ });
61
+ // Register tool
62
+ server.registerTool("convert_pdf_page_to_markdown", {
63
+ title: "Convert PDF Page to Markdown",
64
+ description: "Convert a specific page from a PDF file to markdown format using Qwen VL model. The tool first converts the PDF page to an image, then uses AI vision model to extract and format the content as markdown.",
65
+ inputSchema: {
66
+ pdf_path: z.string().describe("Absolute path to the PDF file to convert. The file must exist and be readable."),
67
+ page_number: z.number().describe("Page number to convert (1-indexed). Must be between 1 and the total number of pages in the PDF."),
68
+ },
69
+ }, async ({ pdf_path, page_number }) => {
70
+ try {
71
+ // Validate inputs
72
+ if (!pdf_path || typeof pdf_path !== "string") {
73
+ throw new Error("pdf_path must be a non-empty string");
74
+ }
75
+ if (typeof page_number !== "number" ||
76
+ page_number < 1 ||
77
+ !Number.isInteger(page_number)) {
78
+ throw new Error("page_number must be a positive integer");
79
+ }
80
+ // Check if file exists
81
+ try {
82
+ await fs.access(pdf_path);
83
+ }
84
+ catch {
85
+ throw new Error(`PDF file not found: ${pdf_path}`);
86
+ }
87
+ // Convert PDF page to image
88
+ const imageBuffer = await convertPdfPageToImage(pdf_path, page_number);
89
+ // Convert image to markdown using Qwen VL
90
+ const markdown = await convertImageToMarkdown(imageBuffer, apiUrl, apiKey);
91
+ return {
92
+ content: [
93
+ {
94
+ type: "text",
95
+ text: markdown,
96
+ },
97
+ ],
98
+ };
99
+ }
100
+ catch (error) {
101
+ const errorMessage = error instanceof Error ? error.message : String(error);
102
+ return {
103
+ content: [
104
+ {
105
+ type: "text",
106
+ text: `Error converting PDF page to markdown: ${errorMessage}`,
107
+ },
108
+ ],
109
+ isError: true,
110
+ };
111
+ }
112
+ });
113
+ // Start the server
114
+ const transport = new StdioServerTransport();
115
+ await server.connect(transport);
116
+ console.error("PDF to Markdown MCP server running on stdio");
117
+ }
118
+ try {
119
+ await main();
120
+ }
121
+ catch (error) {
122
+ console.error("Fatal error:", error);
123
+ process.exit(1);
124
+ }
125
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Convert a PDF page to a PNG image buffer
3
+ *
4
+ * Note: This implementation uses pdfjs-dist (legacy build) with node-canvas.
5
+ */
6
+ export declare function convertPdfPageToImage(pdfPath: string, pageNumber: number): Promise<Buffer>;
7
+ //# sourceMappingURL=pdfConverter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pdfConverter.d.ts","sourceRoot":"","sources":["../../src/pdfConverter.ts"],"names":[],"mappings":"AAcA;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAoCjB"}
@@ -0,0 +1,45 @@
1
+ // Polyfill DOM APIs required by pdfjs-dist in Node.js environment
2
+ import { createCanvas } from "canvas";
3
+ import * as fs from "node:fs/promises";
4
+ // Lazy load pdfjs-dist
5
+ let pdfjsLib = null;
6
+ async function getPdfjsLib() {
7
+ if (!pdfjsLib) {
8
+ // @ts-ignore
9
+ pdfjsLib = await import("pdfjs-dist/legacy/build/pdf.mjs");
10
+ }
11
+ return pdfjsLib;
12
+ }
13
+ /**
14
+ * Convert a PDF page to a PNG image buffer
15
+ *
16
+ * Note: This implementation uses pdfjs-dist (legacy build) with node-canvas.
17
+ */
18
+ export async function convertPdfPageToImage(pdfPath, pageNumber) {
19
+ const pdfjsLib = await getPdfjsLib();
20
+ const pdfData = await fs.readFile(pdfPath);
21
+ const loadingTask = pdfjsLib.getDocument({
22
+ data: new Uint8Array(pdfData),
23
+ useWorkerFetch: false,
24
+ isEvalSupported: false,
25
+ useSystemFonts: true,
26
+ // Disable standard font loading to avoid some node issues
27
+ disableFontFace: true,
28
+ });
29
+ const pdfDocument = await loadingTask.promise;
30
+ if (pageNumber < 1 || pageNumber > pdfDocument.numPages) {
31
+ throw new Error(`Invalid page number. PDF has ${pdfDocument.numPages} pages.`);
32
+ }
33
+ const page = await pdfDocument.getPage(pageNumber);
34
+ const viewport = page.getViewport({ scale: 2 });
35
+ const canvas = createCanvas(viewport.width, viewport.height);
36
+ const context = canvas.getContext("2d");
37
+ const renderContext = {
38
+ canvasContext: context,
39
+ viewport: viewport,
40
+ background: "white",
41
+ };
42
+ await page.render(renderContext).promise;
43
+ return canvas.toBuffer("image/png");
44
+ }
45
+ //# sourceMappingURL=pdfConverter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pdfConverter.js","sourceRoot":"","sources":["../../src/pdfConverter.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAEvC,uBAAuB;AACvB,IAAI,QAAQ,GAAQ,IAAI,CAAC;AACzB,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,aAAa;QACb,QAAQ,GAAG,MAAM,MAAM,CAAC,iCAAiC,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,OAAe,EACf,UAAkB;IAElB,MAAM,QAAQ,GAAG,MAAM,WAAW,EAAE,CAAC;IACrC,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAE3C,MAAM,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC;QACvC,IAAI,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC;QAC7B,cAAc,EAAE,KAAK;QACrB,eAAe,EAAE,KAAK;QACtB,cAAc,EAAE,IAAI;QACpB,0DAA0D;QAC1D,eAAe,EAAE,IAAI;KACtB,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC;IAE9C,IAAI,UAAU,GAAG,CAAC,IAAI,UAAU,GAAG,WAAW,CAAC,QAAQ,EAAE,CAAC;QACxD,MAAM,IAAI,KAAK,CACb,gCAAgC,WAAW,CAAC,QAAQ,SAAS,CAC9D,CAAC;IACJ,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,WAAW,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACnD,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;IAEhD,MAAM,MAAM,GAAG,YAAY,CAAC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC7D,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAExC,MAAM,aAAa,GAAG;QACpB,aAAa,EAAE,OAAc;QAC7B,QAAQ,EAAE,QAAQ;QAClB,UAAU,EAAE,OAAO;KACpB,CAAC;IAEF,MAAM,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,OAAO,CAAC;IAEzC,OAAO,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=convertPdfPageToImage.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertPdfPageToImage.test.d.ts","sourceRoot":"","sources":["../../test/convertPdfPageToImage.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,72 @@
1
+ import { convertPdfPageToImage } from "../src/pdfConverter.js";
2
+ import * as fs from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ /**
5
+ * Test for convertPdfPageToImage function
6
+ */
7
+ async function testConvertPdfPageToImage() {
8
+ const testPdfPath = path.join(process.cwd(), "test", "test.pdf");
9
+ console.log("Test 1: Convert valid PDF page to image");
10
+ try {
11
+ const imageBuffer = await convertPdfPageToImage(testPdfPath, 1);
12
+ if (!Buffer.isBuffer(imageBuffer)) {
13
+ throw new Error("Expected Buffer but got: " + typeof imageBuffer);
14
+ }
15
+ if (imageBuffer.length === 0) {
16
+ throw new Error("Image buffer is empty");
17
+ }
18
+ // Verify PNG signature (first 8 bytes)
19
+ const pngSignature = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
20
+ const actualSignature = imageBuffer.slice(0, 8);
21
+ if (!actualSignature.equals(pngSignature)) {
22
+ throw new Error("Generated buffer is not a valid PNG image");
23
+ }
24
+ console.log("✓ Test 1 passed: Successfully converted page 1 to PNG image");
25
+ console.log(` Image size: ${imageBuffer.length} bytes`);
26
+ // Optional: Save test output
27
+ const outputPath = path.join(process.cwd(), "test", "output_page1.png");
28
+ await fs.writeFile(outputPath, imageBuffer);
29
+ console.log(` Test image saved to: ${outputPath}`);
30
+ }
31
+ catch (error) {
32
+ console.error("✗ Test 1 failed:", error);
33
+ throw error;
34
+ }
35
+ console.log("\nTest 2: Handle invalid page number");
36
+ try {
37
+ await convertPdfPageToImage(testPdfPath, 99999);
38
+ console.error("✗ Test 2 failed: Should have thrown error for invalid page number");
39
+ throw new Error("Expected error was not thrown");
40
+ }
41
+ catch (error) {
42
+ if (error.message.includes("Invalid page number")) {
43
+ console.log("✓ Test 2 passed: Correctly rejected invalid page number");
44
+ }
45
+ else {
46
+ console.error("✗ Test 2 failed: Unexpected error:", error);
47
+ throw error;
48
+ }
49
+ }
50
+ console.log("\nTest 3: Handle non-existent file");
51
+ try {
52
+ await convertPdfPageToImage("/nonexistent/file.pdf", 1);
53
+ console.error("✗ Test 3 failed: Should have thrown error for non-existent file");
54
+ throw new Error("Expected error was not thrown");
55
+ }
56
+ catch (error) {
57
+ if (error.code === "ENOENT" || error.message.includes("no such file")) {
58
+ console.log("✓ Test 3 passed: Correctly rejected non-existent file");
59
+ }
60
+ else {
61
+ console.error("✗ Test 3 failed: Unexpected error:", error);
62
+ throw error;
63
+ }
64
+ }
65
+ console.log("\n✅ All tests passed!");
66
+ }
67
+ // Run tests
68
+ testConvertPdfPageToImage().catch((error) => {
69
+ console.error("\n❌ Test suite failed:", error);
70
+ process.exit(1);
71
+ });
72
+ //# sourceMappingURL=convertPdfPageToImage.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertPdfPageToImage.test.js","sourceRoot":"","sources":["../../test/convertPdfPageToImage.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC;;GAEG;AACH,KAAK,UAAU,yBAAyB;IACtC,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAEjE,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;IACvD,IAAI,CAAC;QACH,MAAM,WAAW,GAAG,MAAM,qBAAqB,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;QAEhE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,2BAA2B,GAAG,OAAO,WAAW,CAAC,CAAC;QACpE,CAAC;QAED,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;QAC3C,CAAC;QAED,uCAAuC;QACvC,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;QACnF,MAAM,eAAe,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAEhD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC;YAC1C,MAAM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AAO,CAAC,KAAK,CAAC,iEAAiE,CAAC,CAAC;QACjF,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;YACtE,OAAO,CAAC,GAAG,CAAC,uDAAuD,CAAC,CAAC;QACvE,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YAC3D,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;AACvC,CAAC;AAED,YAAY;AACZ,yBAAyB,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IAC1C,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,KAAK,CAAC,CAAC;IAC/C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "pdf-to-markdown-mcp",
3
+ "version": "1.0.0",
4
+ "description": "MCP server that converts PDF pages to markdown using Qwen VL model",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "scripts": {
8
+ "prebuild": "npm audit --omit=dev --audit-level=moderate",
9
+ "build": "tsc",
10
+ "start": "node dist/index.js",
11
+ "dev": "tsc --watch",
12
+ "test": "tsc && node dist/test/convertPdfPageToImage.test.js"
13
+ },
14
+ "keywords": [
15
+ "mcp",
16
+ "pdf",
17
+ "markdown",
18
+ "qwen"
19
+ ],
20
+ "author": "",
21
+ "license": "MIT",
22
+ "dependencies": {
23
+ "@modelcontextprotocol/sdk": "^1.25.2",
24
+ "canvas": "^3.2.0",
25
+ "pdfjs-dist": "^4.8.69"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^22.10.2",
29
+ "typescript": "^5.7.2"
30
+ }
31
+ }
package/src/index.ts ADDED
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import * as fs from "node:fs/promises";
6
+ import { z } from "zod";
7
+ import { convertPdfPageToImage } from "./pdfConverter.js";
8
+
9
+ interface QwenVLResponse {
10
+ output?: {
11
+ text?: string;
12
+ };
13
+ message?: string;
14
+ }
15
+
16
+ /**
17
+ * Call Qwen VL API to convert image to markdown
18
+ */
19
+ async function convertImageToMarkdown(
20
+ imageBuffer: Buffer,
21
+ apiUrl: string,
22
+ apiKey: string
23
+ ): Promise<string> {
24
+ const base64Image = imageBuffer.toString("base64");
25
+
26
+ const requestBody = {
27
+ model: "qwen-vl-max",
28
+ input: {
29
+ messages: [
30
+ {
31
+ role: "user",
32
+ content: [
33
+ {
34
+ image: `data:image/png;base64,${base64Image}`,
35
+ },
36
+ {
37
+ text: "Please convert this image to markdown format. Extract all text, tables, and structure accurately.",
38
+ },
39
+ ],
40
+ },
41
+ ],
42
+ },
43
+ };
44
+
45
+ const response = await fetch(apiUrl, {
46
+ method: "POST",
47
+ headers: {
48
+ "Content-Type": "application/json",
49
+ Authorization: `Bearer ${apiKey}`,
50
+ },
51
+ body: JSON.stringify(requestBody),
52
+ });
53
+
54
+ if (!response.ok) {
55
+ const errorText = await response.text();
56
+ throw new Error(
57
+ `Qwen API request failed: ${response.status} ${response.statusText} - ${errorText}`
58
+ );
59
+ }
60
+
61
+ const result = (await response.json()) as QwenVLResponse;
62
+
63
+ if (result.output?.text) {
64
+ return result.output.text;
65
+ }
66
+
67
+ throw new Error(
68
+ `Unexpected API response format: ${JSON.stringify(result)}`
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Main server setup
74
+ */
75
+ async function main() {
76
+ const apiUrl = process.env.QWEN_API_URL;
77
+ const apiKey = process.env.QWEN_API_KEY;
78
+
79
+ if (!apiUrl || !apiKey) {
80
+ throw new Error(
81
+ "Missing required environment variables: QWEN_API_URL and QWEN_API_KEY must be set"
82
+ );
83
+ }
84
+
85
+ const server = new McpServer({
86
+ name: "pdf-to-markdown-mcp",
87
+ version: "1.0.0",
88
+ });
89
+
90
+ // Register tool
91
+ server.registerTool(
92
+ "convert_pdf_page_to_markdown",
93
+ {
94
+ title: "Convert PDF Page to Markdown",
95
+ description:
96
+ "Convert a specific page from a PDF file to markdown format using Qwen VL model. The tool first converts the PDF page to an image, then uses AI vision model to extract and format the content as markdown.",
97
+ inputSchema: {
98
+ pdf_path: z.string().describe(
99
+ "Absolute path to the PDF file to convert. The file must exist and be readable."
100
+ ),
101
+ page_number: z.number().describe(
102
+ "Page number to convert (1-indexed). Must be between 1 and the total number of pages in the PDF."
103
+ ),
104
+ },
105
+ },
106
+ async ({ pdf_path, page_number }) => {
107
+ try {
108
+ // Validate inputs
109
+ if (!pdf_path || typeof pdf_path !== "string") {
110
+ throw new Error("pdf_path must be a non-empty string");
111
+ }
112
+
113
+ if (
114
+ typeof page_number !== "number" ||
115
+ page_number < 1 ||
116
+ !Number.isInteger(page_number)
117
+ ) {
118
+ throw new Error("page_number must be a positive integer");
119
+ }
120
+
121
+ // Check if file exists
122
+ try {
123
+ await fs.access(pdf_path);
124
+ } catch {
125
+ throw new Error(`PDF file not found: ${pdf_path}`);
126
+ }
127
+
128
+ // Convert PDF page to image
129
+ const imageBuffer = await convertPdfPageToImage(pdf_path, page_number);
130
+
131
+ // Convert image to markdown using Qwen VL
132
+ const markdown = await convertImageToMarkdown(
133
+ imageBuffer,
134
+ apiUrl,
135
+ apiKey
136
+ );
137
+
138
+ return {
139
+ content: [
140
+ {
141
+ type: "text",
142
+ text: markdown,
143
+ },
144
+ ],
145
+ };
146
+ } catch (error) {
147
+ const errorMessage =
148
+ error instanceof Error ? error.message : String(error);
149
+ return {
150
+ content: [
151
+ {
152
+ type: "text",
153
+ text: `Error converting PDF page to markdown: ${errorMessage}`,
154
+ },
155
+ ],
156
+ isError: true,
157
+ };
158
+ }
159
+ }
160
+ );
161
+
162
+ // Start the server
163
+ const transport = new StdioServerTransport();
164
+ await server.connect(transport);
165
+
166
+ console.error("PDF to Markdown MCP server running on stdio");
167
+ }
168
+
169
+ try {
170
+ await main();
171
+ } catch (error) {
172
+ console.error("Fatal error:", error);
173
+ process.exit(1);
174
+ }
@@ -0,0 +1,59 @@
1
+ // Polyfill DOM APIs required by pdfjs-dist in Node.js environment
2
+ import { createCanvas } from "canvas";
3
+ import * as fs from "node:fs/promises";
4
+
5
+ // Lazy load pdfjs-dist
6
+ let pdfjsLib: any = null;
7
+ async function getPdfjsLib() {
8
+ if (!pdfjsLib) {
9
+ // @ts-ignore
10
+ pdfjsLib = await import("pdfjs-dist/legacy/build/pdf.mjs");
11
+ }
12
+ return pdfjsLib;
13
+ }
14
+
15
+ /**
16
+ * Convert a PDF page to a PNG image buffer
17
+ *
18
+ * Note: This implementation uses pdfjs-dist (legacy build) with node-canvas.
19
+ */
20
+ export async function convertPdfPageToImage(
21
+ pdfPath: string,
22
+ pageNumber: number
23
+ ): Promise<Buffer> {
24
+ const pdfjsLib = await getPdfjsLib();
25
+ const pdfData = await fs.readFile(pdfPath);
26
+
27
+ const loadingTask = pdfjsLib.getDocument({
28
+ data: new Uint8Array(pdfData),
29
+ useWorkerFetch: false,
30
+ isEvalSupported: false,
31
+ useSystemFonts: true,
32
+ // Disable standard font loading to avoid some node issues
33
+ disableFontFace: true,
34
+ });
35
+
36
+ const pdfDocument = await loadingTask.promise;
37
+
38
+ if (pageNumber < 1 || pageNumber > pdfDocument.numPages) {
39
+ throw new Error(
40
+ `Invalid page number. PDF has ${pdfDocument.numPages} pages.`
41
+ );
42
+ }
43
+
44
+ const page = await pdfDocument.getPage(pageNumber);
45
+ const viewport = page.getViewport({ scale: 2 });
46
+
47
+ const canvas = createCanvas(viewport.width, viewport.height);
48
+ const context = canvas.getContext("2d");
49
+
50
+ const renderContext = {
51
+ canvasContext: context as any,
52
+ viewport: viewport,
53
+ background: "white",
54
+ };
55
+
56
+ await page.render(renderContext).promise;
57
+
58
+ return canvas.toBuffer("image/png");
59
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=convertPdfPageToImage.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertPdfPageToImage.test.d.ts","sourceRoot":"","sources":["convertPdfPageToImage.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,72 @@
1
+ import { convertPdfPageToImage } from "../src/index.js";
2
+ import * as fs from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ /**
5
+ * Test for convertPdfPageToImage function
6
+ */
7
+ async function testConvertPdfPageToImage() {
8
+ const testPdfPath = path.join(process.cwd(), "test", "DNV_Annual_Report_2024.pdf");
9
+ console.log("Test 1: Convert valid PDF page to image");
10
+ try {
11
+ const imageBuffer = await convertPdfPageToImage(testPdfPath, 1);
12
+ if (!Buffer.isBuffer(imageBuffer)) {
13
+ throw new Error("Expected Buffer but got: " + typeof imageBuffer);
14
+ }
15
+ if (imageBuffer.length === 0) {
16
+ throw new Error("Image buffer is empty");
17
+ }
18
+ // Verify PNG signature (first 8 bytes)
19
+ const pngSignature = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
20
+ const actualSignature = imageBuffer.slice(0, 8);
21
+ if (!actualSignature.equals(pngSignature)) {
22
+ throw new Error("Generated buffer is not a valid PNG image");
23
+ }
24
+ console.log("✓ Test 1 passed: Successfully converted page 1 to PNG image");
25
+ console.log(` Image size: ${imageBuffer.length} bytes`);
26
+ // Optional: Save test output
27
+ const outputPath = path.join(process.cwd(), "test", "output_page1.png");
28
+ await fs.writeFile(outputPath, imageBuffer);
29
+ console.log(` Test image saved to: ${outputPath}`);
30
+ }
31
+ catch (error) {
32
+ console.error("✗ Test 1 failed:", error);
33
+ throw error;
34
+ }
35
+ console.log("\nTest 2: Handle invalid page number");
36
+ try {
37
+ await convertPdfPageToImage(testPdfPath, 99999);
38
+ console.error("✗ Test 2 failed: Should have thrown error for invalid page number");
39
+ throw new Error("Expected error was not thrown");
40
+ }
41
+ catch (error) {
42
+ if (error.message.includes("Invalid page number")) {
43
+ console.log("✓ Test 2 passed: Correctly rejected invalid page number");
44
+ }
45
+ else {
46
+ console.error("✗ Test 2 failed: Unexpected error:", error);
47
+ throw error;
48
+ }
49
+ }
50
+ console.log("\nTest 3: Handle non-existent file");
51
+ try {
52
+ await convertPdfPageToImage("/nonexistent/file.pdf", 1);
53
+ console.error("✗ Test 3 failed: Should have thrown error for non-existent file");
54
+ throw new Error("Expected error was not thrown");
55
+ }
56
+ catch (error) {
57
+ if (error.code === "ENOENT" || error.message.includes("no such file")) {
58
+ console.log("✓ Test 3 passed: Correctly rejected non-existent file");
59
+ }
60
+ else {
61
+ console.error("✗ Test 3 failed: Unexpected error:", error);
62
+ throw error;
63
+ }
64
+ }
65
+ console.log("\n✅ All tests passed!");
66
+ }
67
+ // Run tests
68
+ testConvertPdfPageToImage().catch((error) => {
69
+ console.error("\n❌ Test suite failed:", error);
70
+ process.exit(1);
71
+ });
72
+ //# sourceMappingURL=convertPdfPageToImage.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertPdfPageToImage.test.js","sourceRoot":"","sources":["convertPdfPageToImage.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC;;GAEG;AACH,KAAK,UAAU,yBAAyB;IACtC,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,4BAA4B,CAAC,CAAC;IAEnF,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;I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AAC,KAAK,EAAE,EAAE;IAC1C,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,KAAK,CAAC,CAAC;IAC/C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,78 @@
1
+ import { convertPdfPageToImage } from "../src/pdfConverter.js";
2
+ import * as fs from "node:fs/promises";
3
+ import * as path from "node:path";
4
+
5
+ /**
6
+ * Test for convertPdfPageToImage function
7
+ */
8
+ async function testConvertPdfPageToImage() {
9
+ const testPdfPath = path.join(process.cwd(), "test", "test.pdf");
10
+
11
+ console.log("Test 1: Convert valid PDF page to image");
12
+ try {
13
+ const imageBuffer = await convertPdfPageToImage(testPdfPath, 1);
14
+
15
+ if (!Buffer.isBuffer(imageBuffer)) {
16
+ throw new Error("Expected Buffer but got: " + typeof imageBuffer);
17
+ }
18
+
19
+ if (imageBuffer.length === 0) {
20
+ throw new Error("Image buffer is empty");
21
+ }
22
+
23
+ // Verify PNG signature (first 8 bytes)
24
+ const pngSignature = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
25
+ const actualSignature = imageBuffer.slice(0, 8);
26
+
27
+ if (!actualSignature.equals(pngSignature)) {
28
+ throw new Error("Generated buffer is not a valid PNG image");
29
+ }
30
+
31
+ console.log("✓ Test 1 passed: Successfully converted page 1 to PNG image");
32
+ console.log(` Image size: ${imageBuffer.length} bytes`);
33
+
34
+ // Optional: Save test output
35
+ const outputPath = path.join(process.cwd(), "test", "output_page1.png");
36
+ await fs.writeFile(outputPath, imageBuffer);
37
+ console.log(` Test image saved to: ${outputPath}`);
38
+ } catch (error) {
39
+ console.error("✗ Test 1 failed:", error);
40
+ throw error;
41
+ }
42
+
43
+ console.log("\nTest 2: Handle invalid page number");
44
+ try {
45
+ await convertPdfPageToImage(testPdfPath, 99999);
46
+ console.error("✗ Test 2 failed: Should have thrown error for invalid page number");
47
+ throw new Error("Expected error was not thrown");
48
+ } catch (error: any) {
49
+ if (error.message.includes("Invalid page number")) {
50
+ console.log("✓ Test 2 passed: Correctly rejected invalid page number");
51
+ } else {
52
+ console.error("✗ Test 2 failed: Unexpected error:", error);
53
+ throw error;
54
+ }
55
+ }
56
+
57
+ console.log("\nTest 3: Handle non-existent file");
58
+ try {
59
+ await convertPdfPageToImage("/nonexistent/file.pdf", 1);
60
+ console.error("✗ Test 3 failed: Should have thrown error for non-existent file");
61
+ throw new Error("Expected error was not thrown");
62
+ } catch (error: any) {
63
+ if (error.code === "ENOENT" || error.message.includes("no such file")) {
64
+ console.log("✓ Test 3 passed: Correctly rejected non-existent file");
65
+ } else {
66
+ console.error("✗ Test 3 failed: Unexpected error:", error);
67
+ throw error;
68
+ }
69
+ }
70
+
71
+ console.log("\n✅ All tests passed!");
72
+ }
73
+
74
+ // Run tests
75
+ testConvertPdfPageToImage().catch((error) => {
76
+ console.error("\n❌ Test suite failed:", error);
77
+ process.exit(1);
78
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022"],
7
+ "outDir": "./dist",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "resolveJsonModule": true,
13
+ "declaration": true,
14
+ "declarationMap": true,
15
+ "sourceMap": true
16
+ },
17
+ "include": ["src/**/*", "test/**/*"],
18
+ "exclude": ["node_modules", "dist"]
19
+ }