i m Wana Delete One page from PDF By imagemagick , How can this be done? this my code this return just one page in pdf ? what the problem ?
$image = new \Imagick(__DIR__.'/test.pdf');
$pageNumber = $image->count();
$page = true;
$imgs = [];
for($i=0 ; $i<$pageNumber ; $i++){
$image->readImage(__DIR__.'/test.pdf['.$i.']');
if($i === 2 && $page == true){
$image->removeImage();
$page = false;
continue;
}
// $imgs[] = __DIR__.'images'.$i.'.jpg';
}
$image->setImageFormat("pdf");
$image->writeImage('images.pdf');
file_put_contents(__DIR__.'images'.$i.'.pdf',$image);
Assuming that the original pdf is having 5 pages (known as fivepage.pdf), then you may use the following steps to remove page 3 from it and generate a new pdf known as combined.pdf
use Imagick to open the pdf
determine the number of pages
loop over each page of this pdf
save the pages into separate , temporary jpeg files
push the jpeg files (except page 3, $i==2) into array
use the array to generate the "combined.pdf"
delete all the temp jpeg files
So the code is:
<?php
$file="./fivepage.pdf";
$im = new Imagick($file);
$resultimages = array();
$noOfPagesInPDF = $im->getNumberImages();
// loop over all the pdf pages
for ($i = 0; $i < $noOfPagesInPDF; $i++) {
$url = $file.'['.$i.']';
$image = new Imagick();
// $image->setResolution(300,300);
// use the above line if you want higher resolution
$image->readimage($url);
$image->setImageFormat("jpg");
$image->writeImage("./temp_".($i+1).'.jpg');
// include all pages except page 3 ($i==2)
if ($i!=2) {
array_push($resultimages, "./temp_".($i+1).'.jpg');
}
}
// generate the resulting pdf (omitting page 3)
$pdf = new Imagick($resultimages);
$pdf->setImageFormat('pdf');
$pdf->writeImages('combined.pdf', true);
// clear temp images
for ($i = 0; $i < $noOfPagesInPDF; $i++) {
unlink("./temp_".($i+1).'.jpg');
}
echo "pdf without page 3 saved";
?>
Related
I'm currently using TCPDI merge four documents into a single PDF and temporarily storing the document using a variable. Is it possible to add "Bates Numbering" to the file, starting with the third page? (The first two pages are a cover letter.) Thanks in advance for pointing me in the right direction
require_once('../tcpdf/tcpdf.php');
require_once('../tcpdf/tcpdi.php');
// Create new PDF document.
$pdf = new TCPDI();
// iterate through the files
foreach ($filesarray AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
// add a page with the same orientation and size
$pdf->AddPage($size['orientation'], $size);
// Set page boxes from imported page 1.
$pdf->setPageFormatFromTemplatePage($pageNo, $size['orientation']);
// use the imported page
$pdf->useTemplate($templateId);
}
}
// Output the new PDF
$attachment = $pdf->Output("Merged.pdf", "S");
I'm not familiar with Bates System but what i did was add the Page number as a Label and check your PageNo variable/index to determine when to show your batesNo.
For the labeling. See the TCPDF documentation.
*Code not tested
<?php
// iterate through the files
foreach ($filesarray AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
$batesNo = 0000000001; //initialize*****
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
/***********NEW BLOCK*******/
if ($pageNo > 3) {
$pdf->SetTitle('JonesNo-'.$batesNo);
} else {
$pdf->SetTitle($pageNo);
}
////////////////////////
// add a page with the same orientation and size
$pdf->AddPage($size['orientation'], $size);
// Set page boxes from imported page 1.
$pdf->setPageFormatFromTemplatePage($pageNo, $size['orientation']);
// use the imported page
$pdf->useTemplate($templateId);
}
}
?>
i am using php imagick to create a image and than convert to pdf. using php imagick. i coded this:
$image = new Imagick();
$height = 800; //height of the page;
$image->newImage(794, $height, "#f5f5f5");
$image->setImageFormat("jpg");
$card = new Imagick('card.jpg'); ; //get single card
$l_align = 190; //left alignment
for($i=0; $i < 4; $i++) //for creating multiple cards on a page
{
$image->compositeImage($card, Imagick::COMPOSITE_DEFAULT,10, ($l_align*$i)+10);
$image->compositeImage($card, Imagick::COMPOSITE_DEFAULT, 390, ($l_align*$i)+10);
}
$image->setResolution(72, 72);
$image->resetIterator();
$combined = $image->appendImages(true);
$image->setImageFormat("pdf");
$combined->writeImages( 'card.pdf', true );
header("Content-Type: application/pdf");
header('Content-Disposition: attachment; filename="card.pdf"');
echo file_get_contents('card.pdf');
and get something like this
in pdf format . Now i want to page break after every 6 cards print in pdf . i am using imagick . please help me. thanks in advance.
You are using the wrong function for adding images as new pages. You should be using addImage which adds the new image as a separate page, rather than append which just tacks them onto the bottom of the current image.
An example of this working is:
$combined = null;
$images = [
'../../../images/Source1.jpg',
'../../../images/Source2.png',
];
foreach ($images as $image) {
if ($combined == null) {
$combined = new Imagick(realpath($image));
}
else {
$card = new Imagick(realpath($image)); ; //get single card
$combined->addImage($card);
}
}
$combined->setImageFormat("pdf");
$combined->writeImages( './card.pdf', true );
btw there is weird stuff going on in your code example - you're only even attempting to add one image, and what is 'resetIterator' doing in there?
i am trying to merge two files using FPDI the error i get is:'TCPDF ERROR: File is encrypted!', however, the files are not encrypted, at least the files are printable, viewable etc and no password is required.
i want to merge two files:
http://www.nps.org.au/__data/cmi_pdfs/CMI7412.pdf
http://www.nps.org.au/__data/cmi_pdfs/CMI6656.pdf
after i copy the files to the server and store the file names in array ($files) that has the absolute file paths, my code is:
if (count ($files) > 0 )
{
$pdf = new FPDI();
$pdf->setPrintHeader(FALSE);
$pdf->setPrintFooter(FALSE);
foreach ($files as $file)
{
for ($i = 0; $i < count($files); $i++ )
{
$pagecount = $pdf->setSourceFile($files[$i]);
for($j = 0; $j < $pagecount ; $j++)
{
$tplidx = $pdf->importPage(($j +1), '/MediaBox');
$specs = $pdf->getTemplateSize($tplidx);
if ( $specs['h'] > $specs['w'] )
{
$orientation = 'P';
}
else
{
$orientation = 'L';
}
$pdf->addPage($orientation,'A4');
$pdf->useTemplate($tplidx, 0, 0, 0, 0, TRUE);
}
}
$output = $pdf->Output('', 'S');
foreach ( $files as $file )
{
delete_file($file);
}
}
I have also tried to merge the files using ghostscript, but with no luck.
I tried acrobat pro, which required a password for one file, but when I used mac preview, i exported the file and was able to merge it using acrobat with no issues. i.e. mac preview removed the protection with no problems.
So, what is it about the file CMI7412.pdf that stops merging, but not exporting, viewing, printing? and how can i get around it?
I have tried similar issue and works fine, try it. It can handle different orientations between PDFs.
// array to hold list of PDF files to be merged
$files = array("a.pdf", "b.pdf", "c.pdf");
$pageCount = 0;
// initiate FPDI
$pdf = new FPDI();
// iterate through the files
foreach ($files AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
// create a page (landscape or portrait depending on the imported page size)
if ($size['w'] > $size['h']) {
$pdf->AddPage('L', array($size['w'], $size['h']));
} else {
$pdf->AddPage('P', array($size['w'], $size['h']));
}
// use the imported page
$pdf->useTemplate($templateId);
$pdf->SetFont('Helvetica');
$pdf->SetXY(5, 5);
$pdf->Write(8, 'Generated by FPDI');
}
}
The problem was the encryption in the pdf file, it was protected from changes without a password.
I used qpdf to export a decrypted version of the pdf as a temporary file. Then I used pdftk to join the files. Turns out to be far faster than the PHP libraries.
I have the following php function below that's converting a local PDF file into images. In short, I want each PDF page to be converted to a separate image.
The function converts the PDF to an image - but only the last page. I want every page of the PDF to be converted to a image and numbered. Not just the last page of the PDF.
Currently, this function converts the last page of example.pdf to example-0.jpg. Issue I'm sure lies within the for method. What am I missing?
$file_name = 'example.pdf'; // using just for this example, I pull $file_name from another function
function _create_preview_images($file_name) {
// Strip document extension
$file_name = basename($file_name, '.pdf');
// Convert this document
// Each page to single image
$img = new imagick('uploads/'.$file_name.'.pdf');
// Set background color and flatten
// Prevents black background on objects with transparency
$img->setImageBackgroundColor('white');
$img = $img->flattenImages();
// Set image resolution
// Determine num of pages
$img->setResolution(300,300);
$num_pages = $img->getNumberImages();
// Compress Image Quality
$img->setImageCompressionQuality(100);
// Convert PDF pages to images
for($i = 0;$i < $num_pages; $i++) {
// Set iterator postion
$img->setIteratorIndex($i);
// Set image format
$img->setImageFormat('jpeg');
// Write Images to temp 'upload' folder
$img->writeImage('uploads/'.$file_name.'-'.$i.'.jpg');
}
$img->destroy();
}
Seems like most of my code was correct. The issue was, I was using $img->flattenImages(); incorrectly. This merges a sequence of images into one image. Much like how Photoshop flattens all visible layers into an image when exporting a jpg.
I removed the above line and the individual files were written as expected.
/* convert pdf file to list image files */
if($_FILES['file_any']['type']=='application/pdf'){
$file_name = str_replace(substr($url,0,strpos($url,$_FILES['file_any']['name'])),'',$url);
$basename = substr($file_name,0,strpos($file_name,'.'));
$abcd = wp_upload_dir();
$delpath = $abcd['path'];
$savepath = $abcd['url'];
$dirpath = substr($savepath,(strpos($savepath,'/upl')+1));
$file_name = basename($file_name, '.pdf');
$img = new imagick($delpath.'/'.$file_name.'.pdf');
$img->setImageBackgroundColor('white');
$img->setResolution(300,300);
$num_pages = $img->getNumberImages();
$img->setImageCompressionQuality(100);
$imageurl = NULL;
$imagedelurl = NULL;
for($i = 0;$i < $num_pages; $i++) {
$imageurl[]=$savepath.'/'.$basename.'-'.$i.'.jpg';
$imagedelurl[] = $delpath.'/'.$basename.'-'.$i.'.jpg';
// Set iterator postion
$img->setIteratorIndex($i);
// Set image format
$img->setImageFormat('jpeg');
// Write Images to temp 'upload' folder
$img->writeImage($delpath.'/'.$file_name.'-'.$i.'.jpg');
}
$img->destroy();
}
There is a much easier way without the loop, just use $img->writeImages($filename,false); and it will make a file per PDF-page. As you said, if you flatten the image first, it only saves 1 page.
first install
imagemagick
in your system or server
and then create
pdfimage
folder and put pdf file in this folder then run the code and upload it file
<?php
$file_name = $_FILES['pdfupload']['name']; // using just for this example, I pull $file_name from another function
//echo strpos($file_name,'.pdf');
$basename = substr($file_name,0,strpos($file_name,'.'));
//echo $_FILES['pdfupload']['type'];
//if (isset($_POST['submit'])){
if($_FILES['pdfupload']['type']=='application/pdf'){
// Strip document extension
$file_name = basename($file_name, '.pdf');
// Convert this document
// Each page to single image
$img = new imagick('pdfimage/'.$file_name.'.pdf');
// Set background color and flatten
// Prevents black background on objects with transparency
$img->setImageBackgroundColor('white');
//$img = $img->flattenImages();
// Set image resolution
// Determine num of pages
$img->setResolution(300,300);
$num_pages = $img->getNumberImages();
// Compress Image Quality
$img->setImageCompressionQuality(100);
$images = NULL;
// Convert PDF pages to images
for($i = 0;$i < $num_pages; $i++) {
$images[]=$basename.'-'.$i.'.jpg';
// Set iterator postion
$img->setIteratorIndex($i);
// Set image format
$img->setImageFormat('jpeg');
// Write Images to temp 'upload' folder
$img->writeImage('pdfimage/'.$file_name.'-'.$i.'.jpg');
}
echo "<pre>";
print_r($images);
$img->destroy();
}
//}
?>
This one might be a little confusing. I'm using AMCharts with rails. Amcharts comes with a PHP script to export images called "export.php"
I'm trying to figure out how to take the code in export.php and put it into a controller.
Here is the code:
<?php
// amcharts.com export to image utility
// set image type (gif/png/jpeg)
$imgtype = 'jpeg';
// set image quality (from 0 to 100, not applicable to gif)
$imgquality = 100;
// get data from $_POST or $_GET ?
$data = &$_POST;
// get image dimensions
$width = (int) $data['width'];
$height = (int) $data['height'];
// create image object
$img = imagecreatetruecolor($width, $height);
// populate image with pixels
for ($y = 0; $y < $height; $y++) {
// innitialize
$x = 0;
// get row data
$row = explode(',', $data['r'.$y]);
// place row pixels
$cnt = sizeof($row);
for ($r = 0; $r < $cnt; $r++) {
// get pixel(s) data
$pixel = explode(':', $row[$r]);
// get color
$pixel[0] = str_pad($pixel[0], 6, '0', STR_PAD_LEFT);
$cr = hexdec(substr($pixel[0], 0, 2));
$cg = hexdec(substr($pixel[0], 2, 2));
$cb = hexdec(substr($pixel[0], 4, 2));
// allocate color
$color = imagecolorallocate($img, $cr, $cg, $cb);
// place repeating pixels
$repeat = isset($pixel[1]) ? (int) $pixel[1] : 1;
for ($c = 0; $c < $repeat; $c++) {
// place pixel
imagesetpixel($img, $x, $y, $color);
// iterate column
$x++;
}
}
}
// set proper content type
header('Content-type: image/'.$imgtype);
header('Content-Disposition: attachment; filename="chart.'.$imgtype.'"');
// stream image
$function = 'image'.$imgtype;
if ($imgtype == 'gif') {
$function($img);
}
else {
$function($img, null, $imgquality);
}
// destroy
imagedestroy($img);
?>
There are some versions in existence in a thread I found here: http://www.amcharts.com/forum/viewtopic.php?id=341
But I have a feeling the PHP code above has changed since then - because neither implementation worked for me.
What this code more or less dose is grabs the informations, that were sent to the script (POST).
The informations include the height and width of the picture and the RGB values of every pixel. The script draws every pixel and sends the images at the end to the client.
You can use Rmagick's method to draw a pixel. This will give you the same result.
The incomming post data looks like this:
height = number -> cast to int
width = number -> cast to int
// first row with a repeating part of R:G:B,R:G:B,... (n = width)
r0 = 255:0:0,150:120:0,77:88:99,...
r1 = ...
.
.
r100 = ... -> the row count is the height - 1
Actually, I found a discussion about speeding up pixel by pixel drawing.
So apparently I was running into other errors which made me think the already existing code didnt work. However, the code on the thread I linked to in the original question does in fact work!