500 API-Aufrufe
Etwa $0.050 pro Anruf. Guthaben verfällt nicht.
- Einmalzahlung
- Stapelbar auf jedem Tarif
- 1 Anruf pro Dokument
14,000+ trusted customers
Funktioniert dort, wo Sie bereits bauen
PDF4me holt Sie dort ab, wo Sie sich bereits befinden: in Ihrem Browser, Microsoft Teams, Google Workspace, Ihrer Automatisierungsplattform oder Ihrem eigenen Code.
Echte, ausführbare Beispiele direkt aus unseren Open-Source-Beispielen. Wählen Sie einen Endpunkt und eine Sprache,
Kopieren Sie die gesamte Datei und führen Sie sie aus. Das ist die gesamte 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 }; Richten Sie PDF4me auf eine Rechnung, Quittung, einen Kontoauszug oder einen Vertrag und erhalten Sie strukturiertes JSON zurück, das Sie direkt in Ihre Systeme einfügen können. Für diese Dokumenttypen müssen keine Vorlagen gepflegt werden.

Führen Sie Word- oder HTML-Vorlagen mit Ihrem JSON zusammen, um PDF- oder Word-Dateien zu erzeugen, entweder einzeln oder in großen Mengen.

Generieren Sie hybride E-Rechnungen im Format ZUGFeRD, eine PDF/A-3-Datei mit eingebettetem Rechnungs-XML, die für die B2B-Vorschrift in Deutschland und jedes EN 16931 ERP-System geeignet sind.

Definieren Sie Ihr eigenes Feldschema und extrahieren Sie genau das, was Sie benötigen, oder lassen Sie PDF4me gemischte Stapel automatisch klassifizieren und jedes Dokument nach seinem Typ weiterleiten.

Konvertieren Sie Word- und Excel-Dateien in PDF-Dateien und zurück, führen Sie anschließend Office-Dateien zusammen, teilen Sie sie auf, versehen Sie sie mit Wasserzeichen und schützen Sie sie mit einem Passwort – alles über eine einzige API, ohne dass eine Office-Installation erforderlich ist.

Generieren und betten Sie QR-Codes, Code 128, Data Matrix und über 50 weitere Barcode-Typen ein, lesen Sie diese aus PDFs und Bildern aus oder teilen Sie Dokumentenstapel anhand von Barcode-Trennzeichen auf.

Datenschutz und Sicherheit sind integriert, nicht nachträglich hinzugefügt. Das in der Schweiz ansässige Unternehmen PDF4me wendet dieselben Regeln für den Umgang mit Daten an, egal ob Sie eine Datei im Browser konvertieren oder Millionen über die API verarbeiten.
Uploads werden im Ruhezustand verschlüsselt in einem isolierten Cloud-Speicher abgelegt und anschließend innerhalb einer Stunde über Online-Tools oder innerhalb weniger Minuten nach Abschluss eines API-Jobs automatisch gelöscht. Freigabelinks sind 14 Tage gültig. Wir speichern nur die Dateien, die Sie explizit in „Meine Dokumente“ speichern.
Ihre Dokumentinhalte werden niemals für das Modelltraining – weder für unser noch für das von Dritten – gespeichert. Die KI-Extraktion basiert ausschließlich auf dem Schema, das Sie bei der Anfrage definieren. Wir analysieren, extrahieren oder verkaufen die von Ihnen gesendeten Dateien nicht weiter.
Benötigen Sie eine Datenschutzvereinbarung für Beschaffungs- oder DSGVO-Prüfungen? Laden Sie die PDF4me-Vereinbarung sowie die Anhänge zu Verarbeitung und Sicherheit herunter. Teilen Sie diese direkt mit der Rechtsabteilung, ohne auf einen Vertriebsthread warten zu müssen.
Jeder Browser-Upload, API-Aufruf und Download erfolgt über HTTPS/TLS. Während eine Datei zur Verarbeitung gespeichert wird, bleibt sie im Ruhezustand verschlüsselt, mandantenisoliert und wird nur für die Dauer des jeweiligen Vorgangs im Speicher gehalten.
Wir implementieren ein formales Informationssicherheitsmanagementsystem nach ISO/IEC 27001: dokumentierte Richtlinien, rollenbasierte Zugriffskontrolle, Änderungskontrolle, Reaktion auf Sicherheitsvorfälle und Lieferantenüberwachung. Für 2026 ist ein unabhängiges Audit geplant.
Eine Plattform für alltägliche PDF-Tools und eine produktionsreife REST-API mit SDKs, Automatisierungskonnektoren (Make, Zapier, Power Automate, n8n) und MCP. Integrieren Sie Dokumentfunktionen in Ihr Produkt, ohne einen eigenen PDF-Stack entwickeln zu müssen.
Konvertieren, bearbeiten, zusammenführen, komprimieren, signieren und OCR nutzen – kostenlos im Browser. Keine Installation, keine Registrierung.
Nutzen Sie die API kostenlos und laden Sie anschließend Guthabenpakete auf, die unbegrenzt gültig sind. Einmalige Zahlung, keine Vertragsbindung – alle Pakete sind in einem Monatsabo kombinierbar.
Etwa $0.050 pro Anruf. Guthaben verfällt nicht.
Etwa $0.045 pro Anruf. Guthaben verfällt nicht.
Etwa $0.038 pro Anruf. Guthaben verfällt nicht.
Etwa $0.036 pro Anruf. Guthaben verfällt nicht.
Etwa $0.033 pro Anruf. Guthaben verfällt nicht.
Etwa $0.026 pro Anruf. Guthaben verfällt nicht.
Benötigen Sie mehr als unser größtes Prepaid-Paket? Kontaktieren Sie unseren Vertrieb für individuelle Mengenpreise, Zahlungsbedingungen und persönlichen Support.
Ein API-Aufruf pro Dokument. Hochwertige Konvertierungen, OCR und KI-Funktionen zählen als ein Aufruf pro Seite. Benötigen Sie ein Monatsabo oder die kostenlose Version? Alle Informationen finden Sie auf der vollständigen Preisseite.
Die vollständige Preisliste und die Kosten für API-Aufrufe finden Sie hier.Integrieren Sie es mit der API in Ihr Produkt, automatisieren Sie es ohne Programmierung oder nutzen Sie die kostenlosen Tools in Ihrem Browser. Keine Kreditkarte erforderlich.
curl -X POST https://api.pdf4me.com/v1/ConvertToPdfKostenloses Angebot · Keine Kreditkarte erforderlich