create new PDF using TCPDF and import existing PDF into it
Asked Answered
F

3

12

How can I import an existing pdf file into the new-created pdf using TCPDF?

So assume I am currently doing an invoice section. Once the user click print invoice, I will start gather the data and then create a PDF using TCPDF. However, I need to "attach" another existing PDF into it if available. So assume, in 1 invoice file that is generated from TCPDF consists of 5 pages. And then I have to "attach" another existing PDF into this file. So total will be 6 pages or more, depends on the existing PDF file. The existing PDF file is uploaded by the user. So, the existing PDF file will be uploaded first, then will be added into the new generated invoice file.

Is there any way to achieve it?

Featherston answered 29/11, 2016 at 5:26 Comment(2)
import is working fine for me but it is removing the existing images from the imported pdf . Is there any fix ?Bashaw
@MohammadIntsar start a new question for this please.Soever
S
17

You can achieve this with the addition of FPDI:

<?php
require_once('tcpdf.php');
require_once('fpdi.php');

$pdf = new FPDI();

//Merging of the existing PDF pages to the final PDF
$pageCount = $pdf->setSourceFile('existing_pdf.pdf');
for ($i = 1; $i <= $pageCount; $i++) {
    $tplIdx = $pdf->importPage($i, '/MediaBox');
    $pdf->AddPage();
    $pdf->useTemplate($tplIdx);
}

//Your code relative to the invoice here

$pdf->Output();
Soever answered 29/11, 2016 at 8:27 Comment(1)
It remove the existing images from the imported pdf . Is there any fix ?Bashaw
R
1

I have used TCPDI (an extension for TCPDF). You can find it on github https://github.com/pauln/tcpdi. There are also forks ready for composer.

It's easy to use... TCPDI extends TCPDF so constuctor parameters are the same

$pdf = new TCPDI(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

Then add the pages from your existing pdf file after your pages

$pagecount = $pdf->setSourceFile($existingPdfPath);
for ($i = 1; $i <= $pagecount; $i++) {
    $tplidx = $pdf->importPage($i);
    $pdf->AddPage();
    $pdf->useTemplate($tplidx);
}
Ringside answered 16/4, 2020 at 18:35 Comment(0)
K
0

I was solving similar problem and I ended up with merging the PDFs using GhostScript from PHP:

exec('gs -o ' . $merged_path
    . ' -sDEVICE=pdfwrite -dDPFSETTINGS=/prepress '
    . $first_pdf_path . ' '
    . $attachment_path);

It is working for several years just fine.

Keystone answered 29/11, 2016 at 8:8 Comment(3)
I have no idea what is it sirFeatherston
GhostScript is a tool to work with PDFs. I don't know about a way to do that in TCPDF only and the way using GhostScript is very simple. The above line merges two PDFs (first_pdf, attachment) into merged.Keystone
Explaining what you don't understand would be useful if you are interested in solving this issue.Keystone

© 2022 - 2024 — McMap. All rights reserved.