AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(pdfcrowd): let AI agents convert, merge and split PDFs (#16565)
Odai Ahmadd956e2749ef2
diff --git a/bun.lock b/bun.lockindex 59328e380d2..025f1980bc2 100644--- a/bun.lock+++ b/bun.lock@@ -6974,13 +6974,14 @@},"packages/pieces/community/pdfcrowd": {"name": "@activepieces/piece-pdfcrowd",- "version": "0.2.1",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","form-data": "^4.0.6",+ "undici": "7.29.1",},"devDependencies": {"tslib": "^2.3.0",diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex 974275e517e..b42c511b470 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,14 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### Pdfcrowd 0.3.0: Convert URL to PDF and Convert HTML to PDF are builder-only++Convert URL to PDF and Convert HTML to PDF are no longer offered to AI agents. They keep working in flows, but an agent that used them as tools loses them after the upgrade.++#### What you need to do++Agents that used these actions switch to Convert to PDF, which takes a URL or HTML. Flow steps keep running on the version they were built with until you upgrade them.+#### Retell AI 0.3.0: New Call fires only when a call starts, and webhooks must be signedThe **New Call** trigger used to run the flow on every Retell webhook event for a call (started, ended and analyzed), so one call could start the flow three times. From Retell AI 0.3.0 it runs once per call, on the `call_started` event. Deliveries are also checked against Retell's `X-Retell-Signature` header (signed with your API key), and unsigned, forged, stale or repeated deliveries are ignored.diff --git a/packages/pieces/community/pdfcrowd/package.json b/packages/pieces/community/pdfcrowd/package.jsonindex f4e68ce8f15..ecd2e87c0e6 100644--- a/packages/pieces/community/pdfcrowd/package.json+++ b/packages/pieces/community/pdfcrowd/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-pdfcrowd",- "version": "0.2.1",+ "version": "0.3.0","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",@@ -9,7 +9,8 @@"@activepieces/pieces-framework": "workspace:*","form-data": "^4.0.6","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {"tslib": "^2.3.0"diff --git a/packages/pieces/community/pdfcrowd/src/i18n/translation.json b/packages/pieces/community/pdfcrowd/src/i18n/translation.jsonindex 235b05e2575..1aebe4e87aa 100644--- a/packages/pieces/community/pdfcrowd/src/i18n/translation.json+++ b/packages/pieces/community/pdfcrowd/src/i18n/translation.json@@ -7,9 +7,25 @@"Your Pdfcrowd API credentials. Get them at https://pdfcrowd.com/user/account/": "Your Pdfcrowd API credentials. Get them at https://pdfcrowd.com/user/account/","Convert URL to PDF": "Convert URL to PDF","Convert HTML to PDF": "Convert HTML to PDF",+ "Convert to PDF": "Convert to PDF",+ "Convert to Image": "Convert to Image",+ "Merge PDFs": "Merge PDFs",+ "Extract or Remove PDF Pages": "Extract or Remove PDF Pages",+ "Convert PDF to Image": "Convert PDF to Image",+ "Extract Text from PDF": "Extract Text from PDF",+ "Convert PDF to HTML": "Convert PDF to HTML",+ "Convert Image to PDF": "Convert Image to PDF","Custom API Call": "Custom API Call","Convert a web page URL to PDF document": "Convert a web page URL to PDF document","Convert HTML content (string) to PDF document": "Convert HTML content (string) to PDF document",+ "Convert a web page URL or an HTML string to a PDF file.": "Convert a web page URL or an HTML string to a PDF file.",+ "Take a screenshot of a web page URL or an HTML string as an image file.": "Take a screenshot of a web page URL or an HTML string as an image file.",+ "Join two or more PDF files into one PDF, in the order given.": "Join two or more PDF files into one PDF, in the order given.",+ "Create a new PDF that keeps only, or leaves out, the pages you list.": "Create a new PDF that keeps only, or leaves out, the pages you list.",+ "Render PDF pages as images. Several pages come back as one ZIP file.": "Render PDF pages as images. Several pages come back as one ZIP file.",+ "Get the text of a PDF as plain text and as a .txt file.": "Get the text of a PDF as plain text and as a .txt file.",+ "Convert a PDF to a single HTML file with images, styles and fonts embedded.": "Convert a PDF to a single HTML file with images, styles and fonts embedded.",+ "Turn an image (PNG, JPG, GIF, TIFF, WebP and more) into a PDF.": "Turn an image (PNG, JPG, GIF, TIFF, WebP and more) into a PDF.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","URL": "URL","Output Filename": "Output Filename",@@ -118,6 +134,21 @@"Page Background": "Page Background","Multipage Background": "Multipage Background","HTML Content": "HTML Content",+ "HTML": "HTML",+ "Margin": "Margin",+ "File Name": "File Name",+ "Image Format": "Image Format",+ "Width (px)": "Width (px)",+ "Height (px)": "Height (px)",+ "PDF Files": "PDF Files",+ "PDF File": "PDF File",+ "Mode": "Mode",+ "Pages": "Pages",+ "Resolution (DPI)": "Resolution (DPI)",+ "Ignore Layout": "Ignore Layout",+ "Remove Hyphenation": "Remove Hyphenation",+ "Image File": "Image File",+ "Fit": "Fit","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -234,6 +265,35 @@"Apply the first page of a background PDF to every page of the output PDF. Use this to add letterheads, branded templates, or decorative backgrounds that appear behind your content. Backgrounds appear beneath content, while watermarks layer on top. Perfect for adding company letterheads to reports or applying branded templates to dynamically generated content.": "Apply the first page of a background PDF to every page of the output PDF. Use this to add letterheads, branded templates, or decorative backgrounds that appear behind your content. Backgrounds appear beneath content, while watermarks layer on top. Perfect for adding company letterheads to reports or applying branded templates to dynamically generated content.","Apply each page of a background PDF to the corresponding page of the output PDF. Use this for page-specific backgrounds where each page needs a different template - for example, different letterheads for front and back pages. If the background has fewer pages than the output, the last background page is repeated for remaining pages.": "Apply each page of a background PDF to the corresponding page of the output PDF. Use this for page-specific backgrounds where each page needs a different template - for example, different letterheads for front and back pages. If the background has fewer pages than the output, the last background page is repeated for remaining pages.","The HTML content to convert to PDF": "The HTML content to convert to PDF",+ "http(s) address of the page to convert. Leave empty when giving HTML.": "http(s) address of the page to convert. Leave empty when giving HTML.",+ "HTML markup to convert. Leave empty when giving a URL.": "HTML markup to convert. Leave empty when giving a URL.",+ "Defaults to A4.": "Defaults to A4.",+ "Defaults to portrait.": "Defaults to portrait.",+ "Margin on all four sides with a unit, e.g. 10mm. Defaults to 0.4in.": "Margin on all four sides with a unit, e.g. 10mm. Defaults to 0.4in.",+ "HTML shown at the top of every page.": "HTML shown at the top of every page.",+ "HTML shown at the bottom of every page.": "HTML shown at the bottom of every page.",+ "Name of the PDF file. Defaults to document.pdf.": "Name of the PDF file. Defaults to document.pdf.",+ "http(s) address of the page to capture. Leave empty when giving HTML.": "http(s) address of the page to capture. Leave empty when giving HTML.",+ "HTML markup to render. Leave empty when giving a URL.": "HTML markup to render. Leave empty when giving a URL.",+ "Image width in pixels, 96 to 65000. Defaults to 1024.": "Image width in pixels, 96 to 65000. Defaults to 1024.",+ "Image height in pixels. Leave empty to capture the full page height.": "Image height in pixels. Leave empty to capture the full page height.",+ "Name of the image file. Defaults to screenshot.": "Name of the image file. Defaults to screenshot.",+ "The PDFs to merge, in order. At least two.": "The PDFs to merge, in order. At least two.",+ "Name of the merged PDF. Defaults to merged.pdf.": "Name of the merged PDF. Defaults to merged.pdf.",+ "Comma-separated pages or ranges, e.g. 1,3-5 or 2- (to the end).": "Comma-separated pages or ranges, e.g. 1,3-5 or 2- (to the end).",+ "Name of the new PDF. Defaults to pages.pdf.": "Name of the new PDF. Defaults to pages.pdf.",+ "Pages to render, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.": "Pages to render, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.",+ "Defaults to 144. Use 72-96 for screen, 300 for print.": "Defaults to 144. Use 72-96 for screen, 300 for print.",+ "Name without extension (.zip when several pages). Defaults to page.": "Name without extension (.zip when several pages). Defaults to page.",+ "Pages to extract, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.": "Pages to extract, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.",+ "Return text in reading order instead of keeping the page layout.": "Return text in reading order instead of keeping the page layout.",+ "Join words split by a hyphen at the end of a line.": "Join words split by a hyphen at the end of a line.",+ "Name of the text file. Defaults to document.txt.": "Name of the text file. Defaults to document.txt.",+ "Pages to convert, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.": "Pages to convert, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.",+ "Name of the HTML file. Defaults to document.html.": "Name of the HTML file. Defaults to document.html.",+ "Leave empty for the Pdfcrowd default.": "Leave empty for the Pdfcrowd default.",+ "Margin on all four sides with a unit, e.g. 10mm or 0.5in.": "Margin on all four sides with a unit, e.g. 10mm or 0.5in.",+ "Name of the PDF. Defaults to image.pdf.": "Name of the PDF. Defaults to image.pdf.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",@@ -293,6 +353,16 @@"24.04": "24.04","20.10": "20.10","18.10": "18.10",+ "Portrait": "Portrait",+ "Landscape": "Landscape",+ "PNG": "PNG",+ "JPG": "JPG",+ "WebP": "WebP",+ "Keep only these pages": "Keep only these pages",+ "Remove these pages": "Remove these pages",+ "Original size": "Original size",+ "Fit to page": "Fit to page",+ "Stretch to page": "Stretch to page","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/pdfcrowd/src/index.ts b/packages/pieces/community/pdfcrowd/src/index.tsindex 51e647b8378..74fbdcf5673 100644--- a/packages/pieces/community/pdfcrowd/src/index.ts+++ b/packages/pieces/community/pdfcrowd/src/index.ts@@ -2,6 +2,14 @@ import { createPiece } from '@activepieces/pieces-framework';import { pdfcrowdAuth } from './lib/common/auth';import { urlToPdfAction } from './lib/actions/url-to-pdf';import { htmlToPdfAction } from './lib/actions/html-to-pdf';+import { convertToPdfAiAction } from './lib/actions/convert-to-pdf-ai';+import { convertToImageAction } from './lib/actions/convert-to-image';+import { mergePdfsAction } from './lib/actions/merge-pdfs';+import { editPdfPagesAction } from './lib/actions/edit-pdf-pages';+import { pdfToImageAction } from './lib/actions/pdf-to-image';+import { pdfToTextAction } from './lib/actions/pdf-to-text';+import { pdfToHtmlAction } from './lib/actions/pdf-to-html';+import { imageToPdfAction } from './lib/actions/image-to-pdf';import { PieceCategory } from '@activepieces/pieces-framework';import { createCustomApiCallAction } from '@activepieces/pieces-common';import { BASE_URL } from './lib/common/client';@@ -18,6 +26,14 @@ export const pdfcrowd = createPiece({actions: [urlToPdfAction,htmlToPdfAction,+ convertToPdfAiAction,+ convertToImageAction,+ mergePdfsAction,+ editPdfPagesAction,+ pdfToImageAction,+ pdfToTextAction,+ pdfToHtmlAction,+ imageToPdfAction,createCustomApiCallAction({auth: pdfcrowdAuth,baseUrl: () => BASE_URL,diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/convert-to-image.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/convert-to-image.tsnew file mode 100644index 00000000000..974b2a17b9e--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/convert-to-image.ts@@ -0,0 +1,94 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { conversionOutputSchema, pdfcrowdConvert, pickSource, withExtension } from '../common/convert';++export const convertToImageAction = createAction({+ auth: pdfcrowdAuth,+ name: 'convert_to_image',+ displayName: 'Convert to Image',+ description: 'Take a screenshot of a web page URL or an HTML string as an image file.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Renders either a public web page (URL) or an HTML string to an image (PNG, JPG or WebP) with Pdfcrowd, e.g. for previews, thumbnails or social cards. Give exactly one of URL or HTML. Width defaults to 1024 px; without a height the whole page is captured. Returns the image as a file reference. Each call is a fresh conversion that creates a new file and consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: conversionOutputSchema,+ props: {+ url: Property.ShortText({+ displayName: 'URL',+ description: 'http(s) address of the page to capture. Leave empty when giving HTML.',+ required: false,+ }),+ html: Property.LongText({+ displayName: 'HTML',+ description: 'HTML markup to render. Leave empty when giving a URL.',+ required: false,+ }),+ output_format: Property.StaticDropdown({+ displayName: 'Image Format',+ required: true,+ defaultValue: 'png',+ options: {+ options: [+ { label: 'PNG', value: 'png' },+ { label: 'JPG', value: 'jpg' },+ { label: 'WebP', value: 'webp' },+ ],+ },+ }),+ screenshot_width: Property.Number({+ displayName: 'Width (px)',+ description: 'Image width in pixels, 96 to 65000. Defaults to 1024.',+ required: false,+ }),+ screenshot_height: Property.Number({+ displayName: 'Height (px)',+ description: 'Image height in pixels. Leave empty to capture the full page height.',+ required: false,+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the image file. Defaults to screenshot.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const source = pickSource({ url: propsValue.url, html: propsValue.html });+ const format = propsValue.output_format ?? 'png';+ if (!['png', 'jpg', 'webp'].includes(format)) {+ throw new Error('Image Format must be png, jpg or webp.');+ }+ const width = optionalInteger({ value: propsValue.screenshot_width, label: 'Width' });+ const height = optionalInteger({ value: propsValue.screenshot_height, label: 'Height' });+ if (width !== undefined && (width < 96 || width > 65000)) {+ throw new Error('Width must be between 96 and 65000 pixels.');+ }+ if (height !== undefined && height < 1) {+ throw new Error('Height must be a positive number of pixels.');+ }+ return pdfcrowdConvert({+ auth,+ files,+ filename: withExtension({ name: propsValue.filename, fallback: 'screenshot', extension: format }),+ fields: {+ ...source,+ output_format: format,+ screenshot_width: width,+ screenshot_height: height,+ },+ });+ },+});++function optionalInteger({ value, label }: { value: unknown; label: string }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const parsed = Number(value);+ if (!Number.isInteger(parsed)) {+ throw new Error(`${label} must be a whole number of pixels.`);+ }+ return parsed;+}diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/convert-to-pdf-ai.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/convert-to-pdf-ai.tsnew file mode 100644index 00000000000..b6fcf011736--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/convert-to-pdf-ai.ts@@ -0,0 +1,89 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { conversionOutputSchema, pdfcrowdConvert, pickSource, withExtension } from '../common/convert';++export const convertToPdfAiAction = createAction({+ auth: pdfcrowdAuth,+ name: 'convert_to_pdf_ai',+ displayName: 'Convert to PDF',+ description: 'Convert a web page URL or an HTML string to a PDF file.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Converts either a public web page (URL) or an HTML string into a PDF file with Pdfcrowd. Give exactly one of URL or HTML. Optional page size, orientation, one margin applied to all sides, and header/footer HTML (use <span class="pdfcrowd-page-number"></span> and <span class="pdfcrowd-page-count"></span> for page numbers). Returns the PDF as a file reference plus page count and remaining credits. Each call is a fresh conversion that creates a new file and consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: conversionOutputSchema,+ props: {+ url: Property.ShortText({+ displayName: 'URL',+ description: 'http(s) address of the page to convert. Leave empty when giving HTML.',+ required: false,+ }),+ html: Property.LongText({+ displayName: 'HTML',+ description: 'HTML markup to convert. Leave empty when giving a URL.',+ required: false,+ }),+ page_size: Property.StaticDropdown({+ displayName: 'Page Size',+ description: 'Defaults to A4.',+ required: false,+ options: {+ options: ['A3', 'A4', 'A5', 'Letter'].map((v) => ({ label: v, value: v })),+ },+ }),+ orientation: Property.StaticDropdown({+ displayName: 'Orientation',+ description: 'Defaults to portrait.',+ required: false,+ options: {+ options: [+ { label: 'Portrait', value: 'portrait' },+ { label: 'Landscape', value: 'landscape' },+ ],+ },+ }),+ margin: Property.ShortText({+ displayName: 'Margin',+ description: 'Margin on all four sides with a unit, e.g. 10mm. Defaults to 0.4in.',+ required: false,+ }),+ header_html: Property.LongText({+ displayName: 'Header HTML',+ description: 'HTML shown at the top of every page.',+ required: false,+ }),+ footer_html: Property.LongText({+ displayName: 'Footer HTML',+ description: 'HTML shown at the bottom of every page.',+ required: false,+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the PDF file. Defaults to document.pdf.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const source = pickSource({ url: propsValue.url, html: propsValue.html });+ const margin = propsValue.margin?.trim();+ return pdfcrowdConvert({+ auth,+ files,+ filename: withExtension({ name: propsValue.filename, fallback: 'document', extension: 'pdf' }),+ fields: {+ ...source,+ page_size: propsValue.page_size,+ orientation: propsValue.orientation,+ margin_top: margin,+ margin_right: margin,+ margin_bottom: margin,+ margin_left: margin,+ header_html: propsValue.header_html,+ footer_html: propsValue.footer_html,+ },+ });+ },+});diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/edit-pdf-pages.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/edit-pdf-pages.tsnew file mode 100644index 00000000000..25c4f63b231--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/edit-pdf-pages.ts@@ -0,0 +1,59 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { baseName, conversionOutputSchema, pdfcrowdConvert, requireFile, withExtension } from '../common/convert';++export const editPdfPagesAction = createAction({+ auth: pdfcrowdAuth,+ name: 'edit_pdf_pages',+ displayName: 'Extract or Remove PDF Pages',+ description: 'Create a new PDF that keeps only, or leaves out, the pages you list.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Builds a new PDF from one PDF file with Pdfcrowd: mode "extract" keeps only the listed pages, mode "delete" keeps every page except the listed ones. Pages are a comma-separated list of numbers or ranges, e.g. "1,3-5" or "2-" (page 2 to the end). The original file is not changed. Returns the new PDF as a file reference plus its page count. Each call consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: conversionOutputSchema,+ props: {+ pdf: Property.File({ displayName: 'PDF File', required: true }),+ mode: Property.StaticDropdown({+ displayName: 'Mode',+ required: true,+ defaultValue: 'extract',+ options: {+ options: [+ { label: 'Keep only these pages', value: 'extract' },+ { label: 'Remove these pages', value: 'delete' },+ ],+ },+ }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Comma-separated pages or ranges, e.g. 1,3-5 or 2- (to the end).',+ required: true,+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the new PDF. Defaults to pages.pdf.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const mode = propsValue.mode;+ if (mode !== 'extract' && mode !== 'delete') {+ throw new Error('Mode must be extract or delete.');+ }+ const pages = propsValue.pages?.trim();+ if (!pages) {+ throw new Error('Pages is required, e.g. 1,3-5.');+ }+ return pdfcrowdConvert({+ auth,+ files,+ fields: { input_format: 'pdf', action: mode, page_range: pages },+ attachments: [requireFile({ value: propsValue.pdf, label: 'PDF File', field: 'f_1' })],+ filename: withExtension({ name: baseName({ name: propsValue.filename, fallback: 'pages' }), fallback: 'pages', extension: 'pdf' }),+ });+ },+});diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/html-to-pdf.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/html-to-pdf.tsindex f194f15756c..f00d799e907 100644--- a/packages/pieces/community/pdfcrowd/src/lib/actions/html-to-pdf.ts+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/html-to-pdf.ts@@ -1,17 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';import { pdfcrowdAuth } from '../common/auth';-import { getAuthHeader, getConvertUrl } from '../common/client';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import FormData from 'form-data';+import { conversionOutputSchema, pdfcrowdConvert, readAttachments } from '../common/convert';export const htmlToPdfAction = createAction({name: 'html_to_pdf',classification: 'READ',displayName: 'Convert HTML to PDF',description: 'Convert HTML content (string) to PDF document',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Render a raw HTML string into a PDF file via the Pdfcrowd API, returning the generated document. Choose this when you already have HTML markup (e.g. a generated invoice or report) rather than a live page URL (use Convert URL to PDF for a URL). Supports extensive layout, header/footer, watermark, and security options, plus template data injection. Not idempotent: each call performs a fresh conversion that produces a new file and consumes account credits.', idempotent: false },auth: pdfcrowdAuth,+ outputSchema: conversionOutputSchema,props: {htmlContent: Property.LongText({displayName: 'HTML Content',@@ -685,184 +684,136 @@ export const htmlToPdfAction = createAction({}),},async run(context) {- const { auth, propsValue } = context;-- // Build multipart form data to support file uploads- const formData = new FormData();- formData.append('text', propsValue.htmlContent);-- // Add basic options- const basicOptions = [- 'page_size',- 'page_width',- 'page_height',- 'orientation',- 'margin_top',- 'margin_right',- 'margin_bottom',- 'margin_left',- 'no_margins',- 'print_page_range',- 'content_viewport_width',- 'content_viewport_height',- 'content_fit_mode',- 'remove_blank_pages',- 'header_url',- 'header_html',- 'header_height',- 'footer_url',- 'footer_html',- 'footer_height',- 'no_header_footer_horizontal_margins',- 'exclude_header_on_pages',- 'exclude_footer_on_pages',- 'header_footer_scale_factor',- 'page_numbering_offset',- 'page_watermark_url',- 'multipage_watermark_url',- 'page_background_url',- 'multipage_background_url',- 'page_background_color',- 'use_print_media',- 'no_background',- 'disable_javascript',- 'disable_image_loading',- 'disable_remote_fonts',- 'load_iframes',- 'block_ads',- 'default_encoding',- 'locale',- 'http_auth_user_name',- 'http_auth_password',- 'cookies',- 'verify_ssl_certificates',- 'fail_on_main_url_error',- 'fail_on_any_url_error',- 'css_page_rule_mode',- 'custom_css',- 'custom_javascript',- 'on_load_javascript',- 'custom_http_header',- 'javascript_delay',- 'element_to_convert',- 'element_to_convert_mode',- 'wait_for_element',- 'auto_detect_element_to_convert',- 'readability_enhancements',- 'scale_factor',- 'jpeg_quality',- 'convert_images_to_jpeg',- 'image_dpi',- 'enable_pdf_forms',- 'linearize',- 'encrypt',- 'user_password',- 'owner_password',- 'no_print',- 'no_modify',- 'no_copy',- 'title',- 'subject',- 'author',- 'keywords',- 'extract_meta_tags',- 'page_layout',- 'page_mode',- 'initial_zoom_type',- 'initial_page',- 'initial_zoom',- 'hide_toolbar',- 'hide_menubar',- 'hide_window_ui',- 'fit_window',- 'center_window',- 'display_title',- 'right_to_left',- 'debug_log',- 'tag',- 'http_proxy',- 'https_proxy',- 'layout_dpi',- 'main_document_css_annotation',- 'header_footer_css_annotation',- 'conversion_config',- ];-- for (const opt of basicOptions) {- const value = propsValue[opt as keyof typeof propsValue];- if (value !== undefined && value !== null && value !== '' && value !== false) {- formData.append(opt, String(value));- }+ const { auth, propsValue, files } = context;+ const values: Record<string, unknown> = { ...propsValue };+ const fields: Record<string, unknown> = { text: propsValue.htmlContent };+ for (const opt of BASIC_OPTIONS) {+ fields[opt] = values[opt];}-- // Data template options - only sent when data_string is providedif (propsValue.data_string) {- formData.append('data_string', String(propsValue.data_string));- const dataOptions = [- 'data_format',- 'data_ignore_undefined',- 'data_auto_escape',- 'data_trim_blocks',- 'data_options',- ];- for (const opt of dataOptions) {- const value = propsValue[opt as keyof typeof propsValue];- if (value !== undefined && value !== null && value !== '' && value !== false) {- formData.append(opt, String(value));- }- }- }-- // Add file options (watermarks, backgrounds)- const fileOptions = [- 'page_watermark',- 'multipage_watermark',- 'page_background',- 'multipage_background',- ];-- for (const opt of fileOptions) {- const fileValue = propsValue[opt as keyof typeof propsValue] as { data: Buffer; filename: string } | undefined;- if (fileValue?.data) {- formData.append(opt, fileValue.data, { filename: fileValue.filename || `${opt}.pdf` });+ fields['data_string'] = propsValue.data_string;+ for (const opt of DATA_OPTIONS) {+ fields[opt] = values[opt];}}-- const formBuffer = formData.getBuffer();- const converterVersion = propsValue.converter_version || '24.04';- const response = await httpClient.sendRequest({- method: HttpMethod.POST,- url: getConvertUrl(converterVersion),- headers: {- Authorization: getAuthHeader(auth),- 'User-Agent': 'pdfcrowd-activepieces/1.1.0',- ...formData.getHeaders(),- },- body: formBuffer,- responseType: 'arraybuffer',+ return pdfcrowdConvert({+ auth,+ files,+ fields,+ attachments: readAttachments({ values, fieldNames: FILE_OPTIONS }),+ filename: propsValue.outputFilename || 'document.pdf',+ converterVersion: propsValue.converter_version || undefined,});+ },+});- if (response.status >= 400) {- const errorText = Buffer.from(response.body as ArrayBuffer).toString('utf-8');- throw new Error(`Conversion failed (${response.status}): ${errorText}`);- }-- const filename = propsValue.outputFilename || 'document.pdf';+const BASIC_OPTIONS = [+ 'page_size',+ 'page_width',+ 'page_height',+ 'orientation',+ 'margin_top',+ 'margin_right',+ 'margin_bottom',+ 'margin_left',+ 'no_margins',+ 'print_page_range',+ 'content_viewport_width',+ 'content_viewport_height',+ 'content_fit_mode',+ 'remove_blank_pages',+ 'header_url',+ 'header_html',+ 'header_height',+ 'footer_url',+ 'footer_html',+ 'footer_height',+ 'no_header_footer_horizontal_margins',+ 'exclude_header_on_pages',+ 'exclude_footer_on_pages',+ 'header_footer_scale_factor',+ 'page_numbering_offset',+ 'page_watermark_url',+ 'multipage_watermark_url',+ 'page_background_url',+ 'multipage_background_url',+ 'page_background_color',+ 'use_print_media',+ 'no_background',+ 'disable_javascript',+ 'disable_image_loading',+ 'disable_remote_fonts',+ 'load_iframes',+ 'block_ads',+ 'default_encoding',+ 'locale',+ 'http_auth_user_name',+ 'http_auth_password',+ 'cookies',+ 'verify_ssl_certificates',+ 'fail_on_main_url_error',+ 'fail_on_any_url_error',+ 'css_page_rule_mode',+ 'custom_css',+ 'custom_javascript',+ 'on_load_javascript',+ 'custom_http_header',+ 'javascript_delay',+ 'element_to_convert',+ 'element_to_convert_mode',+ 'wait_for_element',+ 'auto_detect_element_to_convert',+ 'readability_enhancements',+ 'scale_factor',+ 'jpeg_quality',+ 'convert_images_to_jpeg',+ 'image_dpi',+ 'enable_pdf_forms',+ 'linearize',+ 'encrypt',+ 'user_password',+ 'owner_password',+ 'no_print',+ 'no_modify',+ 'no_copy',+ 'title',+ 'subject',+ 'author',+ 'keywords',+ 'extract_meta_tags',+ 'page_layout',+ 'page_mode',+ 'initial_zoom_type',+ 'initial_page',+ 'initial_zoom',+ 'hide_toolbar',+ 'hide_menubar',+ 'hide_window_ui',+ 'fit_window',+ 'center_window',+ 'display_title',+ 'right_to_left',+ 'debug_log',+ 'tag',+ 'http_proxy',+ 'https_proxy',+ 'layout_dpi',+ 'main_document_css_annotation',+ 'header_footer_css_annotation',+ 'conversion_config',+];- const file = await context.files.write({- fileName: filename,- data: Buffer.from(response.body as ArrayBuffer),- });+const DATA_OPTIONS = [+ 'data_format',+ 'data_ignore_undefined',+ 'data_auto_escape',+ 'data_trim_blocks',+ 'data_options',+];- const headers = response.headers || {};- return {- file,- filename,- jobId: headers['x-pdfcrowd-job-id'] || '',- pageCount: headers['x-pdfcrowd-pages'] || '0',- outputSize: headers['x-pdfcrowd-output-size'] || '0',- consumedCredits: headers['x-pdfcrowd-consumed-credits'] || '0',- remainingCredits: headers['x-pdfcrowd-remaining-credits'] || '0',- };- },-});+const FILE_OPTIONS = [+ 'page_watermark',+ 'multipage_watermark',+ 'page_background',+ 'multipage_background',+];diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/image-to-pdf.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/image-to-pdf.tsnew file mode 100644index 00000000000..629f5c85d1c--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/image-to-pdf.ts@@ -0,0 +1,79 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { baseName, conversionOutputSchema, pdfcrowdConvert, requireFile, withExtension } from '../common/convert';++export const imageToPdfAction = createAction({+ auth: pdfcrowdAuth,+ name: 'image_to_pdf',+ displayName: 'Convert Image to PDF',+ description: 'Turn an image (PNG, JPG, GIF, TIFF, WebP and more) into a PDF.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Converts one image file into a PDF with Pdfcrowd. Optional page size (A3, A4, A5, Letter; Pdfcrowd default when empty), orientation, one margin for all sides (e.g. 10mm), and fit mode: "fit" scales the image to the page keeping proportions, "stretch" fills the page ignoring proportions, "default" keeps the original size. Returns the PDF as a file reference. Each call consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: conversionOutputSchema,+ props: {+ image: Property.File({ displayName: 'Image File', required: true }),+ page_size: Property.StaticDropdown({+ displayName: 'Page Size',+ description: 'Leave empty for the Pdfcrowd default.',+ required: false,+ options: {+ options: ['A3', 'A4', 'A5', 'Letter'].map((v) => ({ label: v, value: v })),+ },+ }),+ orientation: Property.StaticDropdown({+ displayName: 'Orientation',+ required: false,+ options: {+ options: [+ { label: 'Portrait', value: 'portrait' },+ { label: 'Landscape', value: 'landscape' },+ ],+ },+ }),+ fit: Property.StaticDropdown({+ displayName: 'Fit',+ required: false,+ options: {+ options: [+ { label: 'Original size', value: 'default' },+ { label: 'Fit to page', value: 'fit' },+ { label: 'Stretch to page', value: 'stretch' },+ ],+ },+ }),+ margin: Property.ShortText({+ displayName: 'Margin',+ description: 'Margin on all four sides with a unit, e.g. 10mm or 0.5in.',+ required: false,+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the PDF. Defaults to image.pdf.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const margin = propsValue.margin?.trim();+ return pdfcrowdConvert({+ auth,+ files,+ fields: {+ input_format: 'image',+ page_size: propsValue.page_size,+ orientation: propsValue.orientation,+ print_page_mode: propsValue.fit,+ margin_top: margin,+ margin_right: margin,+ margin_bottom: margin,+ margin_left: margin,+ },+ attachments: [requireFile({ value: propsValue.image, label: 'Image File', field: 'file' })],+ filename: withExtension({ name: baseName({ name: propsValue.filename, fallback: 'image' }), fallback: 'image', extension: 'pdf' }),+ });+ },+});diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/merge-pdfs.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/merge-pdfs.tsnew file mode 100644index 00000000000..3fbbfe6e196--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/merge-pdfs.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { baseName, conversionOutputSchema, fileOf, pdfcrowdConvert, requireFile, withExtension } from '../common/convert';++export const mergePdfsAction = createAction({+ auth: pdfcrowdAuth,+ name: 'merge_pdfs',+ displayName: 'Merge PDFs',+ description: 'Join two or more PDF files into one PDF, in the order given.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Joins two or more PDF files into a single PDF with Pdfcrowd, keeping the order in which they are listed. Each item must be a PDF file (a file reference from an earlier step or a public URL to the file). Returns the merged PDF as a file reference plus the page count. Each call creates a new file and consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: conversionOutputSchema,+ props: {+ pdfs: Property.Array({+ displayName: 'PDF Files',+ description: 'The PDFs to merge, in order. At least two.',+ required: true,+ properties: {+ file: Property.File({ displayName: 'PDF File', required: true }),+ },+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the merged PDF. Defaults to merged.pdf.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const items = Array.isArray(propsValue.pdfs) ? propsValue.pdfs : [];+ if (items.length < 2) {+ throw new Error('Provide at least two PDF files to merge.');+ }+ const attachments = items.map((item, index) =>+ requireFile({ value: fileOf(item), label: `PDF file #${index + 1}`, field: `f_${index + 1}` }),+ );+ return pdfcrowdConvert({+ auth,+ files,+ fields: { input_format: 'pdf' },+ attachments,+ filename: withExtension({ name: baseName({ name: propsValue.filename, fallback: 'merged' }), fallback: 'merged', extension: 'pdf' }),+ });+ },+});diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-html.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-html.tsnew file mode 100644index 00000000000..163067ce27d--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-html.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { baseName, conversionOutputSchema, pdfcrowdConvert, requireFile, withExtension } from '../common/convert';++export const pdfToHtmlAction = createAction({+ auth: pdfcrowdAuth,+ name: 'pdf_to_html',+ displayName: 'Convert PDF to HTML',+ description: 'Convert a PDF to a single HTML file with images, styles and fonts embedded.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Converts a PDF file to one self-contained HTML file with Pdfcrowd (images, CSS and fonts embedded), keeping the visual layout. Optionally limit to some pages ("1", "2-4", "1,3"). Returns the HTML as a file reference plus the page count; to get plain text instead, use Extract Text from PDF. Each call consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: conversionOutputSchema,+ props: {+ pdf: Property.File({ displayName: 'PDF File', required: true }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Pages to convert, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.',+ required: false,+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the HTML file. Defaults to document.html.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ return pdfcrowdConvert({+ auth,+ files,+ fields: {+ input_format: 'pdf',+ output_format: 'html',+ print_page_range: propsValue.pages?.trim(),+ },+ attachments: [requireFile({ value: propsValue.pdf, label: 'PDF File', field: 'file' })],+ filename: withExtension({ name: baseName({ name: propsValue.filename, fallback: 'document' }), fallback: 'document', extension: 'html' }),+ });+ },+});diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-image.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-image.tsnew file mode 100644index 00000000000..3b58c8536d0--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-image.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { baseName, conversionOutputSchema, pdfcrowdConvert, requireFile } from '../common/convert';++export const pdfToImageAction = createAction({+ auth: pdfcrowdAuth,+ name: 'pdf_to_image',+ displayName: 'Convert PDF to Image',+ description: 'Render PDF pages as images. Several pages come back as one ZIP file.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Renders the pages of a PDF file to images (PNG, JPG or WebP) with Pdfcrowd. Optionally limit to some pages ("1", "2-4", "1,3") and set the resolution in DPI (default 144; 72-96 for screen, 300 for print). If one page is rendered the output is a single image file; if several pages are rendered the output is a ZIP file with one image per page (the file name ends in .zip). Returns a file reference plus the page count. Each call consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: conversionOutputSchema,+ props: {+ pdf: Property.File({ displayName: 'PDF File', required: true }),+ output_format: Property.StaticDropdown({+ displayName: 'Image Format',+ required: true,+ defaultValue: 'png',+ options: {+ options: [+ { label: 'PNG', value: 'png' },+ { label: 'JPG', value: 'jpg' },+ { label: 'WebP', value: 'webp' },+ ],+ },+ }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Pages to render, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.',+ required: false,+ }),+ dpi: Property.Number({+ displayName: 'Resolution (DPI)',+ description: 'Defaults to 144. Use 72-96 for screen, 300 for print.',+ required: false,+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name without extension (.zip when several pages). Defaults to page.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const format = propsValue.output_format ?? 'png';+ if (!['png', 'jpg', 'webp'].includes(format)) {+ throw new Error('Image Format must be png, jpg or webp.');+ }+ const dpi = propsValue.dpi === undefined || propsValue.dpi === null ? undefined : Number(propsValue.dpi);+ if (dpi !== undefined && (!Number.isInteger(dpi) || dpi < 1)) {+ throw new Error('Resolution must be a positive whole number.');+ }+ const name = baseName({ name: propsValue.filename, fallback: 'page' });+ return pdfcrowdConvert({+ auth,+ files,+ fields: {+ input_format: 'pdf',+ output_format: format,+ print_page_range: propsValue.pages?.trim(),+ dpi,+ },+ attachments: [requireFile({ value: propsValue.pdf, label: 'PDF File', field: 'file' })],+ filename: (contentType) => `${name}.${contentType.toLowerCase().includes('zip') ? 'zip' : format}`,+ });+ },+});diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-text.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-text.tsnew file mode 100644index 00000000000..620948afd3a--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/pdf-to-text.ts@@ -0,0 +1,57 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { pdfcrowdAuth } from '../common/auth';+import { baseName, pdfcrowdConvertWithData, requireFile, textConversionOutputSchema, withExtension } from '../common/convert';++export const pdfToTextAction = createAction({+ auth: pdfcrowdAuth,+ name: 'pdf_to_text',+ displayName: 'Extract Text from PDF',+ description: 'Get the text of a PDF as plain text and as a .txt file.',+ audience: 'both',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Extracts the text of a PDF file with Pdfcrowd and returns it directly in the text field (plus a .txt file reference). Optionally limit to some pages ("1", "2-4", "1,3"), ignore the visual layout to get text in reading order, and remove end-of-line hyphenation. Works on PDFs that contain text; scanned images give no text. Each call consumes Pdfcrowd credits.',+ idempotent: false,+ },+ outputSchema: textConversionOutputSchema,+ props: {+ pdf: Property.File({ displayName: 'PDF File', required: true }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Pages to extract, e.g. 1 or 2-4 or 1,3. Leave empty for all pages.',+ required: false,+ }),+ no_layout: Property.Checkbox({+ displayName: 'Ignore Layout',+ description: 'Return text in reading order instead of keeping the page layout.',+ required: false,+ }),+ remove_hyphenation: Property.Checkbox({+ displayName: 'Remove Hyphenation',+ description: 'Join words split by a hyphen at the end of a line.',+ required: false,+ }),+ filename: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the text file. Defaults to document.txt.',+ required: false,+ }),+ },+ async run({ auth, propsValue, files }) {+ const { result, data } = await pdfcrowdConvertWithData({+ auth,+ files,+ fields: {+ input_format: 'pdf',+ output_format: 'txt',+ print_page_range: propsValue.pages?.trim(),+ no_layout: propsValue.no_layout,+ remove_hyphenation: propsValue.remove_hyphenation,+ },+ attachments: [requireFile({ value: propsValue.pdf, label: 'PDF File', field: 'file' })],+ filename: withExtension({ name: baseName({ name: propsValue.filename, fallback: 'document' }), fallback: 'document', extension: 'txt' }),+ });+ return { text: data.toString('utf-8'), ...result };+ },+});diff --git a/packages/pieces/community/pdfcrowd/src/lib/actions/url-to-pdf.ts b/packages/pieces/community/pdfcrowd/src/lib/actions/url-to-pdf.tsindex f2a254739f9..2fd1111ac94 100644--- a/packages/pieces/community/pdfcrowd/src/lib/actions/url-to-pdf.ts+++ b/packages/pieces/community/pdfcrowd/src/lib/actions/url-to-pdf.ts@@ -1,17 +1,16 @@import { createAction, Property } from '@activepieces/pieces-framework';import { pdfcrowdAuth } from '../common/auth';-import { getAuthHeader, getConvertUrl } from '../common/client';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import FormData from 'form-data';+import { conversionOutputSchema, pdfcrowdConvert, readAttachments } from '../common/convert';export const urlToPdfAction = createAction({name: 'url_to_pdf',classification: 'READ',displayName: 'Convert URL to PDF',description: 'Convert a web page URL to PDF document',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Render a publicly accessible web page URL into a PDF file via the Pdfcrowd API, returning the generated document. Choose this when the source is a live URL rather than raw HTML markup (use Convert HTML to PDF for an HTML string). Supports extensive layout, header/footer, watermark, and security options. Not idempotent: each call performs a fresh conversion that produces a new file and consumes account credits.', idempotent: false },auth: pdfcrowdAuth,+ outputSchema: conversionOutputSchema,props: {url: Property.ShortText({displayName: 'URL',@@ -685,184 +684,136 @@ export const urlToPdfAction = createAction({}),},async run(context) {- const { auth, propsValue } = context;-- // Build multipart form data to support file uploads- const formData = new FormData();- formData.append('url', propsValue.url);-- // Add basic options- const basicOptions = [- 'page_size',- 'page_width',- 'page_height',- 'orientation',- 'margin_top',- 'margin_right',- 'margin_bottom',- 'margin_left',- 'no_margins',- 'print_page_range',- 'content_viewport_width',- 'content_viewport_height',- 'content_fit_mode',- 'remove_blank_pages',- 'header_url',- 'header_html',- 'header_height',- 'footer_url',- 'footer_html',- 'footer_height',- 'no_header_footer_horizontal_margins',- 'exclude_header_on_pages',- 'exclude_footer_on_pages',- 'header_footer_scale_factor',- 'page_numbering_offset',- 'page_watermark_url',- 'multipage_watermark_url',- 'page_background_url',- 'multipage_background_url',- 'page_background_color',- 'use_print_media',- 'no_background',- 'disable_javascript',- 'disable_image_loading',- 'disable_remote_fonts',- 'load_iframes',- 'block_ads',- 'default_encoding',- 'locale',- 'http_auth_user_name',- 'http_auth_password',- 'cookies',- 'verify_ssl_certificates',- 'fail_on_main_url_error',- 'fail_on_any_url_error',- 'css_page_rule_mode',- 'custom_css',- 'custom_javascript',- 'on_load_javascript',- 'custom_http_header',- 'javascript_delay',- 'element_to_convert',- 'element_to_convert_mode',- 'wait_for_element',- 'auto_detect_element_to_convert',- 'readability_enhancements',- 'scale_factor',- 'jpeg_quality',- 'convert_images_to_jpeg',- 'image_dpi',- 'enable_pdf_forms',- 'linearize',- 'encrypt',- 'user_password',- 'owner_password',- 'no_print',- 'no_modify',- 'no_copy',- 'title',- 'subject',- 'author',- 'keywords',- 'extract_meta_tags',- 'page_layout',- 'page_mode',- 'initial_zoom_type',- 'initial_page',- 'initial_zoom',- 'hide_toolbar',- 'hide_menubar',- 'hide_window_ui',- 'fit_window',- 'center_window',- 'display_title',- 'right_to_left',- 'debug_log',- 'tag',- 'http_proxy',- 'https_proxy',- 'layout_dpi',- 'main_document_css_annotation',- 'header_footer_css_annotation',- 'conversion_config',- ];-- for (const opt of basicOptions) {- const value = propsValue[opt as keyof typeof propsValue];- if (value !== undefined && value !== null && value !== '' && value !== false) {- formData.append(opt, String(value));- }+ const { auth, propsValue, files } = context;+ const values: Record<string, unknown> = { ...propsValue };+ const fields: Record<string, unknown> = { url: propsValue.url };+ for (const opt of BASIC_OPTIONS) {+ fields[opt] = values[opt];}-- // Data template options - only sent when data_string is providedif (propsValue.data_string) {- formData.append('data_string', String(propsValue.data_string));- const dataOptions = [- 'data_format',- 'data_ignore_undefined',- 'data_auto_escape',- 'data_trim_blocks',- 'data_options',- ];- for (const opt of dataOptions) {- const value = propsValue[opt as keyof typeof propsValue];- if (value !== undefined && value !== null && value !== '' && value !== false) {- formData.append(opt, String(value));- }- }- }-- // Add file options (watermarks, backgrounds)- const fileOptions = [- 'page_watermark',- 'multipage_watermark',- 'page_background',- 'multipage_background',- ];-- for (const opt of fileOptions) {- const fileValue = propsValue[opt as keyof typeof propsValue] as { data: Buffer; filename: string } | undefined;- if (fileValue?.data) {- formData.append(opt, fileValue.data, { filename: fileValue.filename || `${opt}.pdf` });+ fields['data_string'] = propsValue.data_string;+ for (const opt of DATA_OPTIONS) {+ fields[opt] = values[opt];}}-- const formBuffer = formData.getBuffer();- const converterVersion = propsValue.converter_version || '24.04';- const response = await httpClient.sendRequest({- method: HttpMethod.POST,- url: getConvertUrl(converterVersion),- headers: {- Authorization: getAuthHeader(auth),- 'User-Agent': 'pdfcrowd-activepieces/1.1.0',- ...formData.getHeaders(),- },- body: formBuffer,- responseType: 'arraybuffer',+ return pdfcrowdConvert({+ auth,+ files,+ fields,+ attachments: readAttachments({ values, fieldNames: FILE_OPTIONS }),+ filename: propsValue.outputFilename || 'document.pdf',+ converterVersion: propsValue.converter_version || undefined,});+ },+});- if (response.status >= 400) {- const errorText = Buffer.from(response.body as ArrayBuffer).toString('utf-8');- throw new Error(`Conversion failed (${response.status}): ${errorText}`);- }-- const filename = propsValue.outputFilename || 'document.pdf';+const BASIC_OPTIONS = [+ 'page_size',+ 'page_width',+ 'page_height',+ 'orientation',+ 'margin_top',+ 'margin_right',+ 'margin_bottom',+ 'margin_left',+ 'no_margins',+ 'print_page_range',+ 'content_viewport_width',+ 'content_viewport_height',+ 'content_fit_mode',+ 'remove_blank_pages',+ 'header_url',+ 'header_html',+ 'header_height',+ 'footer_url',+ 'footer_html',+ 'footer_height',+ 'no_header_footer_horizontal_margins',+ 'exclude_header_on_pages',+ 'exclude_footer_on_pages',+ 'header_footer_scale_factor',+ 'page_numbering_offset',+ 'page_watermark_url',+ 'multipage_watermark_url',+ 'page_background_url',+ 'multipage_background_url',+ 'page_background_color',+ 'use_print_media',+ 'no_background',+ 'disable_javascript',+ 'disable_image_loading',+ 'disable_remote_fonts',+ 'load_iframes',+ 'block_ads',+ 'default_encoding',+ 'locale',+ 'http_auth_user_name',+ 'http_auth_password',+ 'cookies',+ 'verify_ssl_certificates',+ 'fail_on_main_url_error',+ 'fail_on_any_url_error',+ 'css_page_rule_mode',+ 'custom_css',+ 'custom_javascript',+ 'on_load_javascript',+ 'custom_http_header',+ 'javascript_delay',+ 'element_to_convert',+ 'element_to_convert_mode',+ 'wait_for_element',+ 'auto_detect_element_to_convert',+ 'readability_enhancements',+ 'scale_factor',+ 'jpeg_quality',+ 'convert_images_to_jpeg',+ 'image_dpi',+ 'enable_pdf_forms',+ 'linearize',+ 'encrypt',+ 'user_password',+ 'owner_password',+ 'no_print',+ 'no_modify',+ 'no_copy',+ 'title',+ 'subject',+ 'author',+ 'keywords',+ 'extract_meta_tags',+ 'page_layout',+ 'page_mode',+ 'initial_zoom_type',+ 'initial_page',+ 'initial_zoom',+ 'hide_toolbar',+ 'hide_menubar',+ 'hide_window_ui',+ 'fit_window',+ 'center_window',+ 'display_title',+ 'right_to_left',+ 'debug_log',+ 'tag',+ 'http_proxy',+ 'https_proxy',+ 'layout_dpi',+ 'main_document_css_annotation',+ 'header_footer_css_annotation',+ 'conversion_config',+];- const file = await context.files.write({- fileName: filename,- data: Buffer.from(response.body as ArrayBuffer),- });+const DATA_OPTIONS = [+ 'data_format',+ 'data_ignore_undefined',+ 'data_auto_escape',+ 'data_trim_blocks',+ 'data_options',+];- const headers = response.headers || {};- return {- file,- filename,- jobId: headers['x-pdfcrowd-job-id'] || '',- pageCount: headers['x-pdfcrowd-pages'] || '0',- outputSize: headers['x-pdfcrowd-output-size'] || '0',- consumedCredits: headers['x-pdfcrowd-consumed-credits'] || '0',- remainingCredits: headers['x-pdfcrowd-remaining-credits'] || '0',- };- },-});+const FILE_OPTIONS = [+ 'page_watermark',+ 'multipage_watermark',+ 'page_background',+ 'multipage_background',+];diff --git a/packages/pieces/community/pdfcrowd/src/lib/common/convert.ts b/packages/pieces/community/pdfcrowd/src/lib/common/convert.tsnew file mode 100644index 00000000000..670b9bb399b--- /dev/null+++ b/packages/pieces/community/pdfcrowd/src/lib/common/convert.ts@@ -0,0 +1,205 @@+import { AppConnectionValueForAuthProperty, OutputSchema } from '@activepieces/pieces-framework';+import { httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';+import FormData from 'form-data';+import { pdfcrowdAuth } from './auth';+import { getAuthHeader, getConvertUrl } from './client';++export async function pdfcrowdConvert(params: PdfcrowdConvertParams): Promise<PdfcrowdConversionResult> {+ const { result } = await pdfcrowdConvertWithData(params);+ return result;+}++export async function pdfcrowdConvertWithData({+ auth,+ files,+ fields,+ attachments = [],+ filename,+ converterVersion,+}: PdfcrowdConvertParams): Promise<{ result: PdfcrowdConversionResult; data: Buffer }> {+ const formData = new FormData();+ for (const [key, value] of Object.entries(fields)) {+ if (value === undefined || value === null || value === '') {+ continue;+ }+ formData.append(key, String(value));+ }+ for (const attachment of attachments) {+ formData.append(attachment.field, attachment.data, { filename: attachment.filename });+ }+ const dispatcher = await verifiedTls();+ let response;+ try {+ response = await httpClient.sendRequest(+ {+ method: HttpMethod.POST,+ url: getConvertUrl(converterVersion),+ headers: {+ Authorization: getAuthHeader(auth),+ 'User-Agent': 'pdfcrowd-activepieces/1.1.0',+ ...formData.getHeaders(),+ },+ body: formData.getBuffer(),+ responseType: 'arraybuffer',+ followRedirects: false,+ timeout: CONVERT_TIMEOUT_MS,+ redactBodyInErrors: true,+ },+ { dispatcher },+ );+ } catch (e) {+ if (e instanceof HttpError) {+ const text = decodeBody(e.response.body).trim().slice(0, 1000);+ throw new Error(`Pdfcrowd conversion failed (${e.response.status}): ${text}`);+ }+ if (e instanceof Error && (e.name === 'TimeoutError' || e.name === 'AbortError')) {+ throw new Error(`Pdfcrowd conversion did not finish within ${CONVERT_TIMEOUT_MS / 1000} seconds.`);+ }+ throw new Error(`Could not reach Pdfcrowd: ${e instanceof Error ? e.message : String(e)}`);+ }+ if (response.status < 200 || response.status >= 300) {+ throw new Error(`Pdfcrowd conversion failed (${response.status}): Unexpected response status.`);+ }+ const data = Buffer.from(response.body);+ const headers = response.headers ?? {};+ const fileName = typeof filename === 'function' ? filename(headerValue(headers['content-type']) ?? '') : filename;+ const file = await files.write({ fileName, data });+ const result = {+ file,+ filename: fileName,+ jobId: headerValue(headers['x-pdfcrowd-job-id']) ?? '',+ pageCount: headerValue(headers['x-pdfcrowd-pages']) ?? '0',+ outputSize: headerValue(headers['x-pdfcrowd-output-size']) ?? '0',+ consumedCredits: headerValue(headers['x-pdfcrowd-consumed-credits']) ?? '0',+ remainingCredits: headerValue(headers['x-pdfcrowd-remaining-credits']) ?? '0',+ };+ return { result, data };+}++export function requireFile({ value, label, field }: { value: unknown; label: string; field: string }): PdfcrowdAttachment {+ if (!isFileLike(value)) {+ throw new Error(`${label} must be a file (upload it or pass a file from an earlier step).`);+ }+ return { field, data: Buffer.from(value.data), filename: value.filename || 'input' };+}++export function baseName({ name, fallback }: { name: string | undefined; fallback: string }): string {+ const trimmed = name?.trim();+ if (!trimmed) {+ return fallback;+ }+ const dot = trimmed.lastIndexOf('.');+ return dot > 0 ? trimmed.slice(0, dot) : trimmed;+}++export function readAttachments({ values, fieldNames }: { values: Record<string, unknown>; fieldNames: string[] }): PdfcrowdAttachment[] {+ const attachments: PdfcrowdAttachment[] = [];+ for (const field of fieldNames) {+ const value = values[field];+ if (isFileLike(value)) {+ attachments.push({ field, data: Buffer.from(value.data), filename: value.filename || `${field}.pdf` });+ }+ }+ return attachments;+}++export function pickSource({ url, html }: { url?: string; html?: string }): { url: string } | { text: string } {+ const trimmedUrl = url?.trim();+ const text = html !== undefined && html.trim() !== '' ? html : undefined;+ if (trimmedUrl && text !== undefined) {+ throw new Error('Provide either a URL or HTML, not both.');+ }+ if (trimmedUrl) {+ if (!/^https?:\/\//i.test(trimmedUrl)) {+ throw new Error('The URL must start with http:// or https://.');+ }+ return { url: trimmedUrl };+ }+ if (text !== undefined) {+ return { text };+ }+ throw new Error('Provide a URL or HTML to convert.');+}++export function withExtension({ name, fallback, extension }: { name: string | undefined; fallback: string; extension: string }): string {+ const base = name?.trim() || fallback;+ return base.toLowerCase().endsWith(`.${extension}`) ? base : `${base}.${extension}`;+}++export function fileOf(item: unknown): unknown {+ return typeof item === 'object' && item !== null && 'file' in item ? item.file : undefined;+}++export const conversionOutputSchema: OutputSchema = {+ fields: [+ { key: 'file', label: 'File', format: 'url', description: 'The generated file. Pass it to any step that takes a file.' },+ { key: 'filename', label: 'File Name' },+ { key: 'jobId', label: 'Job ID' },+ { key: 'pageCount', label: 'Page Count', format: 'number', description: 'Pages reported by Pdfcrowd (x-pdfcrowd-pages). 0 when Pdfcrowd does not report it, e.g. for HTML to image and image to PDF.' },+ { key: 'outputSize', label: 'Output Size', format: 'filesize', description: 'Size of the output in bytes.' },+ { key: 'consumedCredits', label: 'Consumed Credits', format: 'number' },+ { key: 'remainingCredits', label: 'Remaining Credits', format: 'number' },+ ],+};+++export const textConversionOutputSchema: OutputSchema = {+ fields: [+ { key: 'text', label: 'Text', description: 'The extracted text.' },+ ...conversionOutputSchema.fields,+ ],+};++function isFileLike(value: unknown): value is { data: Uint8Array; filename?: string } {+ return typeof value === 'object' && value !== null && 'data' in value && value.data instanceof Uint8Array;+}++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++function headerValue(value: string | string[] | undefined): string | undefined {+ if (Array.isArray(value)) {+ return value[0];+ }+ return value;+}++function decodeBody(body: unknown): string {+ if (body instanceof ArrayBuffer) {+ return Buffer.from(body).toString('utf-8');+ }+ if (Buffer.isBuffer(body)) {+ return body.toString('utf-8');+ }+ if (typeof body === 'string') {+ return body;+ }+ return JSON.stringify(body) ?? '';+}++let verifiedTlsAgent: Promise<unknown> | undefined;++const CONVERT_TIMEOUT_MS = 480000;++type PdfcrowdAttachment = { field: string; data: Buffer; filename: string };++type PdfcrowdConvertParams = {+ auth: AppConnectionValueForAuthProperty<typeof pdfcrowdAuth>;+ files: { write: (params: { fileName: string; data: Buffer }) => Promise<string> };+ fields: Record<string, unknown>;+ attachments?: PdfcrowdAttachment[];+ filename: string | ((contentType: string) => string);+ converterVersion?: string;+};++type PdfcrowdConversionResult = {+ file: string;+ filename: string;+ jobId: string;+ pageCount: string;+ outputSize: string;+ consumedCredits: string;+ remainingCredits: string;+};