🎥 Make videos programmatically with React
added basic pdf rendering
benno6767d55c47cd
diff --git a/packages/renderer/src/browser/devtools-commands.ts b/packages/renderer/src/browser/devtools-commands.tsindex ae8a98353c..3003cc3c60 100644--- a/packages/renderer/src/browser/devtools-commands.ts+++ b/packages/renderer/src/browser/devtools-commands.ts@@ -17,6 +17,8 @@ import type {GetFrameTreeResponse,NavigateRequest,NavigateResponse,+ PrintPDFRequest,+ PrintPDFResponse,ReleaseObjectRequest,SetAutoAttachRequest,SetDefaultBackgroundColorOverrideRequest,@@ -241,6 +243,10 @@ export interface Commands {paramsType: [CaptureScreenshotRequest?];returnType: CaptureScreenshotResponse;};+ 'Page.printToPDF': {+ paramsType: [PrintPDFRequest];+ returnType: PrintPDFResponse;+ };'Target.activateTarget': {paramsType: [ActivateTargetRequest];returnType: void;diff --git a/packages/renderer/src/browser/devtools-types.ts b/packages/renderer/src/browser/devtools-types.tsindex 82c16dab11..726a084f73 100644--- a/packages/renderer/src/browser/devtools-types.ts+++ b/packages/renderer/src/browser/devtools-types.ts@@ -625,6 +625,86 @@ export interface CaptureScreenshotResponse {data: string;}+export interface PrintPDFRequest {+ /**+ * Paper orientation. Defaults to false.+ */+ landscape?: boolean;+ /**+ * Display header and footer. Defaults to false.+ */+ displayHeaderFooter?: boolean;+ /**+ * Print background graphics. Defaults to false.+ */+ printBackground?: boolean;+ /**+ * Scale of the webpage rendering. Defaults to 1.+ */+ scale?: number;+ /**+ * Paper width in inches. Defaults to 8.5 inches.+ */+ paperWidth?: number;+ /**+ * Paper height in inches. Defaults to 11 inches.+ */+ paperHeight?: number;+ /**+ * Top margin in inches. Defaults to 1cm (~0.4 inches).+ */+ marginTop?: number;+ /**+ * Bottom margin in inches. Defaults to 1cm (~0.4 inches).+ */+ marginBottom?: number;+ /**+ * Left margin in inches. Defaults to 1cm (~0.4 inches).+ */+ marginLeft?: number;+ /**+ * Right margin in inches. Defaults to 1cm (~0.4 inches).+ */+ marginRight?: number;+ /**+ * Paper ranges to print, one based, e.g., '1-5, 8, 11-13'.+ * Pages are printed in the document order, not in the order specified,+ * and no more than once. Defaults to empty string,+ * which implies the entire document is printed.+ * The page numbers are quietly capped to actual page count of the document,+ * and ranges beyond the end of the document are ignored.+ * If this results in no pages to print, an error is reported.+ * It is an error to specify a range with start greater than end.+ */+ pageRanges?: string;+ /**+ * HTML template for the print header.+ * Should be valid HTML markup with following classes used to inject printing values into them:+ * date: formatted print date+ * title: document title+ * url: document location+ * pageNumber: current page number+ * totalPages: total pages in the document+ * For example, <span class=title></span> would generate span containing the title.+ */+ headerTemplate?: string;+ /**+ * HTML template for the print footer. Should use the same format as the headerTemplate.+ */+ footerTemplate?: string;+ /**+ * Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.+ */+ preferCSSPageSize?: boolean;+}++export interface PrintPDFResponse {+ /**+ * Base64-encoded pdf data. Empty if |returnAsStream| is specified. (Encoded as a base64 string when passed over JSON)+ */+ data: string;+}+export interface RequestWillBeSentEvent {/*** Request identifier.diff --git a/packages/renderer/src/get-frame-padded-index.ts b/packages/renderer/src/get-frame-padded-index.tsindex 3266898f19..55659911a0 100644--- a/packages/renderer/src/get-frame-padded-index.ts+++ b/packages/renderer/src/get-frame-padded-index.ts@@ -3,6 +3,8 @@// - If `--every-nth-frame` is passed, only frames 0, 2, 4 are rendered// - If an image sequence is created, the filenames should correspond to the frame numbers: element-099.jpg, element-100.jpg+import type {ImageFormat} from './image-format';+export type CountType = 'from-zero' | 'actual-frames';const padIndex = ({@@ -25,7 +27,7 @@ export const getFrameOutputFileName = ({}: {index: number;frame: number;- imageFormat: 'png' | 'jpeg' | 'none';+ imageFormat: ImageFormat;countType: CountType;lastFrame: number;totalFrames: number;diff --git a/packages/renderer/src/image-format.ts b/packages/renderer/src/image-format.tsindex 9689897194..9d3366ac20 100644--- a/packages/renderer/src/image-format.ts+++ b/packages/renderer/src/image-format.ts@@ -3,11 +3,12 @@import type {PixelFormat} from './pixel-format';-export const validImageFormats = ['png', 'jpeg', 'none'] as const;+export const validImageFormats = ['png', 'jpeg', 'pdf', 'none'] as const;export type ImageFormat = typeof validImageFormats[number];+export type ImageFormatWithoutNone = Exclude<ImageFormat, 'none'>;-export type StillImageFormat = 'png' | 'jpeg';+export type StillImageFormat = ImageFormatWithoutNone;// However, the CLI will override it and use JPEG if suitable.export const DEFAULT_IMAGE_FORMAT: ImageFormat = 'png';@@ -45,7 +46,7 @@ export const validateSelectedPixelFormatAndImageFormatCombination = (};export const validateNonNullImageFormat = (imageFormat: ImageFormat) => {- if (imageFormat !== 'jpeg' && imageFormat !== 'png') {- throw new TypeError('Image format should be either "png" or "jpeg"');+ if (!['jpeg', 'png', 'pdf'].includes(imageFormat)) {+ throw new TypeError('Image format should be either "png", "jpeg" or "pdf"');}};diff --git a/packages/renderer/src/puppeteer-screenshot.ts b/packages/renderer/src/puppeteer-screenshot.tsindex e655847039..8a592e2eef 100644--- a/packages/renderer/src/puppeteer-screenshot.ts+++ b/packages/renderer/src/puppeteer-screenshot.ts@@ -1,12 +1,12 @@import * as assert from 'assert';import type {ClipRegion} from 'remotion';import type {Page} from './browser/BrowserPage';-import type {StillImageFormat} from './image-format';+import type {ImageFormatWithoutNone, StillImageFormat} from './image-format';import {screenshotTask} from './screenshot-task';export const screenshot = (options: {page: Page;- type: 'png' | 'jpeg';+ type: ImageFormatWithoutNone;path?: string;quality?: number;omitBackground: boolean;@@ -14,13 +14,13 @@ export const screenshot = (options: {height: number;clipRegion: ClipRegion | null;}): Promise<Buffer | string> => {- let screenshotType: 'png' | 'jpeg' | null = null;+ let screenshotType: ImageFormatWithoutNone | null = null;// options.type takes precedence over inferring the type from options.path// because it may be a 0-length file with no extension created beforehand// (i.e. as a temp file).if (options.type) {assert.ok(- options.type === 'png' || options.type === 'jpeg',+ ['png', 'jpeg', 'pdf'].includes(options.type),'Unknown options.type value: ' + options.type);screenshotType = options.type;@@ -32,6 +32,7 @@ export const screenshot = (options: {if (extension === 'png') screenshotType = 'png';else if (extension === 'jpg' || extension === 'jpeg')screenshotType = 'jpeg';+ else if (extension === 'pdf') screenshotType = 'pdf';assert.ok(screenshotType,`Unsupported screenshot type for extension \`.${extension}\``diff --git a/packages/renderer/src/screenshot-dom-element.ts b/packages/renderer/src/screenshot-dom-element.tsindex 40891054c9..9413999c1c 100644--- a/packages/renderer/src/screenshot-dom-element.ts+++ b/packages/renderer/src/screenshot-dom-element.ts@@ -25,7 +25,7 @@ export const screenshotDOMElement = async ({}): Promise<Buffer> => {const {path} = opts;- if (imageFormat === 'png') {+ if (['png', 'pdf'].includes(imageFormat)) {await puppeteerEvaluateWithCatch({pageFunction: () => {document.body.style.background = 'transparent';diff --git a/packages/renderer/src/screenshot-task.ts b/packages/renderer/src/screenshot-task.tsindex a655d21165..97aafb3cae 100644--- a/packages/renderer/src/screenshot-task.ts+++ b/packages/renderer/src/screenshot-task.ts@@ -41,28 +41,42 @@ export const screenshotTask = async ({const cap = startPerfMeasure('capture');try {- const result = await client.send('Page.captureScreenshot', {- format,- quality,- clip:- clipRegion !== null && clipRegion !== 'hide'- ? {- x: clipRegion.x,- y: clipRegion.y,- height: clipRegion.height,- scale: 1,- width: clipRegion.width,- }- : {- x: 0,- y: 0,- height,- scale: 1,- width,- },- captureBeyondViewport: true,- optimizeForSpeed: true,- });+ let result;+ if (format === 'pdf') {+ result = await client.send('Page.printToPDF', {+ paperWidth: width / 96, // Convert to Inch+ paperHeight: height / 96, // Convert to Inch+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ scale: 1,+ printBackground: true,+ });+ } else {+ result = await client.send('Page.captureScreenshot', {+ format,+ quality,+ clip:+ clipRegion !== null && clipRegion !== 'hide'+ ? {+ x: clipRegion.x,+ y: clipRegion.y,+ height: clipRegion.height,+ scale: 1,+ width: clipRegion.width,+ }+ : {+ x: 0,+ y: 0,+ height,+ scale: 1,+ width,+ },+ captureBeyondViewport: true,+ optimizeForSpeed: true,+ });+ }stopPerfMeasure(cap);if (shouldSetDefaultBackground)diff --git a/packages/renderer/src/take-frame-and-compose.ts b/packages/renderer/src/take-frame-and-compose.tsindex fb5de7ac12..c5da983b02 100644--- a/packages/renderer/src/take-frame-and-compose.ts+++ b/packages/renderer/src/take-frame-and-compose.ts@@ -60,14 +60,14 @@ export const takeFrameAndCompose = async ({}const needsComposing =- clipRegion === null+ clipRegion === null || imageFormat === 'pdf' // TODO figure out what composing does? null: {tmpFile: path.join(downloadMap.compositingDir,`${frame}.${imageFormat}`),- finalOutfie:+ finalOutFile:output ??path.join(downloadMap.compositingDir,@@ -117,13 +117,13 @@ export const takeFrameAndCompose = async ({},},].filter(truthy),- output: needsComposing.finalOutfie,+ output: needsComposing.finalOutFile,downloadMap,imageFormat: imageFormat === 'jpeg' ? 'Jpeg' : 'Png',});if (wantsBuffer) {- const buffer = await fs.promises.readFile(needsComposing.finalOutfie);- await fs.promises.unlink(needsComposing.finalOutfie);+ const buffer = await fs.promises.readFile(needsComposing.finalOutFile);+ await fs.promises.unlink(needsComposing.finalOutFile);return {buffer, collectedAssets};}}