Add Image to PDF in Node.js
Contents
[
Hide
]
Add an image to an existing PDF file
It is commonly believed that adding images to PDF files requires a complex special tool. However, with Aspose.PDF for Node.js you can quickly and easily add the images you need to PDF in Node.js environment.
We can add images to the end of the file only, therefore right example is we have some scanned document pages and convert them into a single PDF.
In case you want to add images, you can use AsposePdfAddImage function. Please check the following code snippet in order to add images in Node.js environment.
CommonJS:
- Call
require
and importasposepdfnodejs
module asAsposePdf
variable. - Specify the name of the PDF file in which the image will be added.
- Call
AsposePdf
as Promise and perform the operation for adding image. Receive the object if successful. - Call the function AsposePdfAddImage.
- Add image to end a PDF. Thus, if ‘json.errorCode’ is 0, the result of the operation is saved in “ResultAddImage.pdf”. If the json.errorCode parameter is not 0 and, accordingly, an error appears in your file, the error information will be contained in ‘json.errorText’.
const AsposePdf = require('asposepdfnodejs');
const pdf_file = 'Aspose.pdf';
const image_file = 'Aspose.jpg';
AsposePdf().then(AsposePdfModule => {
/*Add an image to end a PDF-file and save the "ResultImage.pdf"*/
const json = AsposePdfModule.AsposePdfAddImage(pdf_file, image_file, "ResultAddImage.pdf");
console.log("AsposePdfAddImage => %O", json.errorCode == 0 ? json.fileNameResult : json.errorText);
});
ECMAScript/ES6:
- Import the
asposepdfnodejs
module. - Specify the name of the PDF file in which the image will be added.
- Initialize the AsposePdf module. Receive the object if successful.
- Call the function AsposePdfAddImage.
- Add image to end a PDF. Thus, if ‘json.errorCode’ is 0, the result of the operation is saved in “ResultAddImage.pdf”. If the json.errorCode parameter is not 0 and, accordingly, an error appears in your file, the error information will be contained in ‘json.errorText’.
import AsposePdf from 'asposepdfnodejs';
const AsposePdfModule = await AsposePdf();
const pdf_file = 'Aspose.pdf';
const image_file = 'Aspose.jpg';
/*Add an image to end a PDF-file and save the "ResultImage.pdf"*/
const json = AsposePdfModule.AsposePdfAddImage(pdf_file, image_file, "ResultAddImage.pdf");
console.log("AsposePdfAddImage => %O", json.errorCode == 0 ? json.fileNameResult : json.errorText);