跳到主要内容
API门户

构建 PDF4me API 所需的一切。

获取 API 密钥,调用一个 REST 端点即可完成所有文档操作,然后发货。支持转换、OCR 识别、合并、生成和条形码标注任何语言的文档。

快速入门

生活三步走。

  • 1. 拿到钥匙。 在控制面板中创建账户并生成 API 密钥。
  • 2. 调用端点。 将 base64 文档和 JSON 选项 POST 到 https://api.pdf4me.com/api/v2/<Action>.
  • 3. 获取你的文件。 响应返回已处理的文件;耗时较长的作业返回一个状态 URL 以供轮询。
https://api.pdf4me.com/api/v2/<Action> Authorization: Basic <api-key> JSON 输入,文件输出
convert-to-pdf.sh
curl -X POST https://api.pdf4me.com/api/v2/ConvertToPdf \
  -H "Authorization: Basic YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "docContent": "<base64 file>",
    "docName": "input.docx"
  }'
对于开发者

专为开发者设计。

真实、可运行的示例,直接取自我们的开源示例。选择一个端点和一种语言,
复制整个文件并运行它。这就是全部的API。

const fs = require('fs');
const path = require('path');

/**
 * Document to PDF Converter using PDF4Me API
 * Converts various document formats (DOCX, XLSX, etc.) to PDF documents
 * Supports both synchronous and asynchronous processing with retry logic
 */

// API Configuration - PDF4Me service for converting documents to PDF
const API_KEY = "get the API key from https://dev.pdf4me.com/dashboard/#/api-keys/";
const BASE_URL = "https://api.pdf4me.com/";
const API_ENDPOINT = `${BASE_URL}api/v2/ConvertToPdf`;

// File paths configuration
const INPUT_DOC_PATH = "sample.docx";           // Path to input document file
const OUTPUT_PDF_PATH = "Document_to_PDF_output.pdf"; // Output PDF file name

// Retry configuration for async processing
const MAX_RETRIES = 10;
const RETRY_DELAY = 10000; // 10 seconds in milliseconds

/**
 * Main function that orchestrates the document to PDF conversion process
 * Handles file validation, conversion, and result processing
 */
async function convertDocumentToPdf() {
    console.log("Starting Document to PDF Conversion Process...");
    console.log("This converts various document formats (DOCX, XLSX, etc.) to PDF");
    console.log("Supports Word documents, Excel spreadsheets, and other formats");
    console.log("-".repeat(60));

    try {
        // Validate input file exists
        if (!fs.existsSync(INPUT_DOC_PATH)) {
            throw new Error(`Input document file not found: ${INPUT_DOC_PATH}`);
        }

        console.log(`Converting: ${INPUT_DOC_PATH} → ${OUTPUT_PDF_PATH}`);

        // Process the conversion
        const result = await processDocumentToPdfConversion();

        // Handle the result
        await handleConversionResult(result);

    } catch (error) {
        console.error("Conversion failed:", error.message);
        process.exit(1);
    }
}

/**
 * Core conversion logic - handles the API request and response processing
 * Supports both synchronous (200) and asynchronous (202) responses
 */
async function processDocumentToPdfConversion() {
    // Read and encode document file to base64
    console.log("Reading and encoding document file...");
    const docContent = fs.readFileSync(INPUT_DOC_PATH);
    const docBase64 = docContent.toString('base64');
    console.log("Document file successfully encoded to base64");

    // Prepare the conversion payload
    const payload = {
        docContent: docBase64,           // Base64 encoded document content
        docName: "output",               // Name for the output file
        async: true                      // Enable asynchronous processing
    };

    // Set up HTTP headers for authentication and content type
    const headers = {
        "Authorization": `Basic ${API_KEY}`,
        "Content-Type": "application/json"
    };

    console.log("Sending request to PDF4Me API...");

    // Make the initial API request
    const response = await fetch(API_ENDPOINT, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(payload)
    });

    console.log(`Status code: ${response.status}`);

    // Handle different response scenarios
    if (response.status === 202) {
        // Asynchronous processing - poll for completion
        console.log("Request accepted. PDF4Me is processing asynchronously...");
        
        const locationUrl = response.headers.get('Location');
        if (!locationUrl) {
            throw new Error("No 'Location' header found in the response for polling");
        }

        return await pollForCompletion(locationUrl, headers);

    } else if (response.status === 200) {
        // Synchronous processing - immediate result
        console.log("Document to PDF conversion completed immediately!");
        return await response.arrayBuffer();

    } else {
        // Error response
        const errorText = await response.text();
        throw new Error(`API request failed. Status: ${response.status}, Response: ${errorText}`);
    }
}

/**
 * Handles the conversion result and saves the PDF file
 * Supports both binary PDF data and base64 encoded responses
 */
async function handleConversionResult(result) {
    try {
        // Convert ArrayBuffer to Buffer for file operations
        const buffer = Buffer.from(result);
        
        // Validate that we have a PDF (check for PDF header)
        if (buffer.length > 4 && buffer.toString('ascii', 0, 4) === '%PDF') {
            console.log("Response is a valid PDF file");
            fs.writeFileSync(OUTPUT_PDF_PATH, buffer);
            console.log(`PDF saved successfully to: ${OUTPUT_PDF_PATH}`);
            console.log("Document has been converted to PDF format");
            return;
        }

        // Try to parse as JSON if not a direct PDF
        try {
            const jsonResponse = JSON.parse(buffer.toString());
            console.log("Successfully parsed JSON response");
            
            // Look for PDF data in different possible JSON locations
            let pdfBase64 = null;
            if (jsonResponse.document && jsonResponse.document.docData) {
                pdfBase64 = jsonResponse.document.docData;  // Common location 1
            } else if (jsonResponse.docData) {
                pdfBase64 = jsonResponse.docData;           // Common location 2
            } else if (jsonResponse.data) {
                pdfBase64 = jsonResponse.data;              // Alternative location
            }

            if (pdfBase64) {
                // Decode base64 PDF data and save to file
                const pdfBytes = Buffer.from(pdfBase64, 'base64');
                fs.writeFileSync(OUTPUT_PDF_PATH, pdfBytes);
                console.log(`PDF saved to ${OUTPUT_PDF_PATH}`);
                console.log("Document has been converted to PDF format");
            } else {
                console.log("No PDF data found in the response.");
                console.log("Full response:", JSON.stringify(jsonResponse, null, 2));
            }

        } catch (jsonError) {
            console.log("Failed to parse JSON response, treating as binary data");
            // If JSON parsing fails, try to save as binary anyway
            if (buffer.length > 1000) {
                fs.writeFileSync(OUTPUT_PDF_PATH, buffer);
                console.log(`PDF saved to ${OUTPUT_PDF_PATH} (as binary data)`);
                console.log("Document has been converted to PDF format");
            } else {
                console.log("Warning: Response doesn't appear to be a valid PDF");
                console.log(`First 100 bytes: ${buffer.toString('hex', 0, 100)}`);
            }
        }

    } catch (error) {
        throw new Error(`Error saving PDF: ${error.message}`);
    }
}

/**
 * Polls the API for async completion with retry logic
 * Handles 202 (processing) and 200 (completed) status codes
 */
async function pollForCompletion(locationUrl, headers) {
    console.log(`Polling URL: ${locationUrl}`);

    for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
        console.log(`Waiting for result... (Attempt ${attempt}/${MAX_RETRIES})`);
        
        // Wait before polling (except on first attempt)
        if (attempt > 1) {
            await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
        }

        try {
            const response = await fetch(locationUrl, {
                method: 'GET',
                headers: headers
            });

            if (response.status === 200) {
                // Conversion completed successfully
                console.log("Document to PDF conversion completed successfully!");
                return await response.arrayBuffer();

            } else if (response.status === 202) {
                // Still processing, continue polling
                console.log("Still processing...");
                continue;

            } else {
                // Error occurred during processing
                const errorText = await response.text();
                throw new Error(`Unexpected error during polling: ${response.status}, Response: ${errorText}`);
            }

        } catch (error) {
            if (attempt === MAX_RETRIES) {
                throw new Error(`Polling failed after ${MAX_RETRIES} attempts: ${error.message}`);
            }
            console.log(`Polling attempt ${attempt} failed: ${error.message}`);
        }
    }

    throw new Error(`Timeout: Document to PDF conversion did not complete after ${MAX_RETRIES} retries`);
}

// Main execution - Run the conversion when script is executed directly
if (require.main === module) {
    convertDocumentToPdf().catch(error => {
        console.error("Fatal error:", error.message);
        process.exit(1);
    });
}

module.exports = { convertDocumentToPdf, processDocumentToPdfConversion, handleConversionResult }; 
门户网站

不仅仅是 API 密钥。

从首次测试到生产部署,所有与端点相关的环节。

键和环境

直接从控制面板生成、轮换和限定每个环境的 API 密钥。

管理密钥

使用情况与分析

密切关注您的通话量,并跟踪使用情况与套餐的对比情况,这样在大规模使用时就不会出现任何意外。

默认异步

长时间运行的作业会返回一个状态 URL,您需要轮询该 URL,直到处理的文件准备就绪。

任何语言,无需SDK

使用基本身份验证标头的普通 HTTPS。可从任何运行时调用;官方库是可选的。

无代码连接器

Zapier、Make、Power Automate 和 n8n 中的相同文档操作。

参见连接器

每个端点的文档

每个操作的参考、请求和响应格式以及复制粘贴示例。

阅读文档

把你的文件准备好。

您可以使用 API 将其集成到您的产品中,无需编写代码即可实现自动化,或者使用浏览器中的免费工具。无需信用卡即可开始。

从一次通话开始curl -X POST https://api.pdf4me.com/v1/ConvertToPdf

免费版 · 无需信用卡