function Redact($input, $output, $vec) { $doc = new PDFDoc($input); if ($doc->InitSecurityHandler()) { Redactor::Redact($doc, $vec); $doc->Save($output, SDFDoc::e_linearized); } }
<?php #--------------------------------------------------------------------------------------- # Copyright (c) 2001-2014 by PDFTron Systems Inc. All Rights Reserved. # Consult LICENSE.txt regarding license information. #--------------------------------------------------------------------------------------- include "../../../PDFNetC/Lib/PDFNetPHP.php"; # This sample illustrates how to edit existing text strings. # Relative path to the folder containing the test files. $input_path = getcwd() . "/../../TestFiles/"; $output_path = $input_path . "Output/"; PDFNet::Initialize(); $doc = new PDFDoc(); $builder = new ElementBuilder(); // ElementBuilder is used to build new Element objects $writer = new ElementWriter(); // ElementWriter is used to write Elements to the page // Start a new page ------------------------------------ $page = $doc->PageCreate(new Rect(0.0, 0.0, 612.0, 794.0)); $writer->Begin($page); // begin writing to the page // Create an Image that can be reused in the document or on the same page. $img = Image::Create($doc->GetSDFDoc(), $input_path . "peppers.jpg"); $element = $builder->CreateImage($img, new Matrix2D((double) ($img->GetImageWidth() / 2), -145.0, 20.0, (double) ($img->GetImageHeight() / 2), 200.0, 150.0)); $writer->WritePlacedElement($element); $gstate = $element->GetGState(); // use the same image (just change its matrix) $gstate->SetTransform(200.0, 0.0, 0.0, 300.0, 50.0, 450.0); $writer->WritePlacedElement($element); // use the same image again (just change its matrix). $writer->WritePlacedElement($builder->CreateImage($img, 300.0, 600.0, 200.0, -150.0));
<?php //--------------------------------------------------------------------------------------- // Copyright (c) 2001-2014 by PDFTron Systems Inc. All Rights Reserved. // Consult LICENSE.txt regarding license information. //--------------------------------------------------------------------------------------- include "../../../PDFNetC/Lib/PDFNetPHP.php"; // Relative path to the folder containing the test files. $input_path = getcwd() . "/../../TestFiles/"; $output_path = $input_path . "Output/"; PDFNet::Initialize(); $doc = new PDFDoc($input_path . "credit card numbers.pdf"); $doc->InitSecurityHandler(); $txt_search = new TextSearch(); $mode = TextSearch::e_whole_word | TextSearch::e_page_stop; $pattern = "joHn sMiTh"; //call Begin() method to initialize the text search. $txt_search->Begin($doc, $pattern, $mode); $step = 0; //call Run() method iteratively to find all matching instances. while (true) { $searchResult = $txt_search->Run(); if ($searchResult->IsFound()) { if ($step == 0) { //step 0: found "John Smith" //note that, here, 'ambient_string' and 'hlts' are not written to, //as 'e_ambient_string' and 'e_highlight' are not set. echo nl2br($searchResult->GetMatch() . "'s credit card number is: \n"); //now switch to using regular expressions to find John's credit card number $mode = $txt_search->GetMode(); $mode |= TextSearch::e_reg_expression | TextSearch::e_highlight;
// image positioning information and DPI. $doc = new PDFDoc($input_path . "newsletter.pdf"); $doc->InitSecurityHandler(); $reader = new ElementReader(); // Read every page for ($itr = $doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) { $reader->Begin($itr->Current()); ImageExtract($reader); $reader->End(); } $doc->Close(); echo nl2br("Done...\n"); echo nl2br("----------------------------------------------------------------\n"); // Example 2: // Extract images by scanning the low-level document. $doc = new PDFDoc($input_path . "newsletter.pdf"); $doc->InitSecurityHandler(); $image_counter = 0; $cos_doc = $doc->GetSDFDoc(); $num_objs = $cos_doc->XRefSize(); for ($i = 1; $i < $num_objs; ++$i) { $obj = $cos_doc->GetObj($i); if ($obj != null && !$obj->IsFree() && $obj->IsStream()) { // Process only images $itr = $obj->Find("Type"); if (!$itr->HasNext() || !($itr->Value()->GetName() == "XObject")) { continue; } $itr = $obj->Find("Subtype"); if (!$itr->HasNext() || !($itr->Value()->GetName() == "Image")) { continue;
$doc->PageInsert($p7, $cover); $doc->PageInsert($p7, $cover); $doc->PageInsert($p7, $cover); // Replicate the cover page two more times by placing it before and after // existing pages. $doc->PagePushFront($cover); $doc->PagePushBack($cover); $doc->Save($output_path . "newsletter_page_clone.pdf", 0); echo nl2br("Done. Result saved in newsletter_page_clone.pdf...\n"); $doc->Close(); // Sample 6 - Use ImportPages() in order to copy multiple pages at once // in order to preserve shared resources between pages (e.g. images, fonts, // colorspaces, etc.) echo nl2br("_______________________________________________\n"); echo nl2br("Sample 6 - Preserving shared resources using ImportPages...\n"); echo nl2br("Opening the input pdf...\n"); $in_doc = new PDFDoc($input_path . "newsletter.pdf"); $in_doc->InitSecurityHandler(); $new_doc = new PDFDoc(); $copy_pages = new VectorPage(); for ($itr = $in_doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) { $copy_pages->push($itr->Current()); } $imported_pages = $new_doc->ImportPages($copy_pages); for ($i = 0; $i < $imported_pages->size(); ++$i) { $new_doc->PagePushFront($imported_pages->get($i)); // Order pages in reverse order. // Use PagePushBack() if you would like to preserve the same order. } $new_doc->Save($output_path . "newsletter_import_pages.pdf", 0); echo nl2br("Done. Result saved in newsletter_import_pages.pdf...\n\n" . "Note that the output file size is less than half the size\n" . "of the file produced using individual page copy operations\n" . "between two documents\n");
$element = $builder->CreateRect(0, 0, $page->GetPageWidth(), $page->GetPageHeight()); $element->SetPathFill(false); $element->SetPathStroke(true); $element->GetGState()->SetLineWidth(40); $writer->WriteElement($element); $writer->End(); // save changes to the current page $doc->PagePushBack($page); // Set the default viewing preference to display 'Layer' tab. $prefs = $doc->GetViewPrefs(); $prefs->SetPageMode(PDFDocViewPrefs::e_UseOC); $doc->Save($output_path . "pdf_layers.pdf", SDFDoc::e_linearized); echo nl2br("Done.\n"); // The following is a code snippet shows how to selectively render // and export PDF layers. $doc = new PDFDoc($output_path . "pdf_layers.pdf"); $doc->InitSecurityHandler(); if (!$doc->HasOC()) { echo nl2br("The document does not contain 'Optional Content'\n"); } else { $init_cfg = $doc->GetOCGConfig(); $ctx = new Context($init_cfg); $pdfdraw = new PDFDraw(); $pdfdraw->SetImageSize(1000, 1000); $pdfdraw->SetOCGContext($ctx); // Render the page using the given OCG context. $page = $doc->GetPage(1); // Get the first page in the document. $pdfdraw->Export($page, $output_path . "pdf_layers_default.png"); // Disable drawing of content that is not optional (i.e. is not part of any layer). $ctx->SetNonOCDrawing(false);
case Element::e_path: $data = $element->GetPathData(); $points = $data->GetPoints(); break; case Element::e_text: $data = $element->GetTextString(); echo nl2br($data . "\n"); break; case Element::e_form: $reader->FormBegin(); ProcessElements($reader); $reader->End(); break; } } } PDFNet::Initialize(); // Extract text data from all pages in the document echo nl2br("__________________________________________________\n"); echo nl2br("Sample 1 - Extract text data from all pages in the document.\n"); echo nl2br("Opening the input pdf...\n"); $doc = new PDFDoc($input_path . "newsletter.pdf"); $doc->InitSecurityHandler(); $pgnum = $doc->GetPageCount(); $page_reader = new ElementReader(); for ($itr = $doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) { $page_reader->Begin($itr->Current()); ProcessElements($page_reader); $page_reader->End(); } echo nl2br("Done.\n");
// (for an example please see PDFPage sample project). // ... } //--------------------------------------------------------------------------------------- PDFNet::Initialize(); // Create a PDF Package. $doc = new PDFDoc(); AddPackage($doc, $input_path . "numbered.pdf", "My File 1"); AddPackage($doc, $input_path . "newsletter.pdf", "My Newsletter..."); AddPackage($doc, $input_path . "peppers.jpg", "An image"); AddCoverPage($doc); $doc->Save($output_path . "package.pdf", SDFDoc::e_linearized); $doc->Close(); echo nl2br("Done.\n"); // Extract parts from a PDF Package. $doc = new PDFDoc($output_path . "package.pdf"); $doc->InitSecurityHandler(); $files = NameTree::Find($doc->GetSDFDoc(), "EmbeddedFiles"); if ($files->IsValid()) { // Traverse the list of embedded files. $i = $files->GetIterator(); for ($counter = 0; $i->HasNext(); $i->Next(), ++$counter) { $entry_name = $i->Key()->GetAsPDFText(); echo nl2br("Part: " . $entry_name . "\n"); $file_spec = new FileSpec($i->Value()); $stm = new Filter($file_spec->GetFileData()); if ($stm) { $stm->WriteToFile($output_path . "extract_" . $counter, false); } } }
$C0->PushBackNumber(0); $C1 = $function->PutArray("C1"); $C1->PushBackNumber(0); $C1->PushBackNumber(1); $C1->PushBackNumber(0); $C1->PushBackNumber(0); $domain = $function->PutArray("Domain"); $domain->PushBackNumber(0); $domain->PushBackNumber(1); $function->PutNumber("FunctionType", 2); $function->PutNumber("N", 1); return $pattern_dict; } //--------------------------------------------------------------------------------------- PDFNet::Initialize(); $doc = new PDFDoc(); $writer = new ElementWriter(); $builder = new ElementBuilder(); // The following sample illustrates how to create and use tiling patterns $page = $doc->PageCreate(); $writer->Begin($page); $element = $builder->CreateTextBegin(Font::Create($doc->GetSDFDoc(), Font::e_times_bold), 1.0); $writer->WriteElement($element); // Begin the text block $data = "G"; $element = $builder->CreateTextRun($data); $element->SetTextMatrix(720.0, 0.0, 0.0, 720.0, 20.0, 240.0); $gs = $element->GetGState(); $gs->SetTextRenderMode(GState::e_fill_stroke_text); $gs->SetLineWidth(4); // Set the fill color space to the Pattern color space.
// Example 1) Simple conversion of a web page to a PDF doc. $doc = new PDFDoc(); // now convert a web page, sending generated PDF pages to doc $converter = new HTML2PDF(); $converter->InsertFromURL($host . $page0); if ($converter->Convert($doc)) { $doc->Save($output_path . "_01.pdf", SDFDoc::e_linearized); } else { echo printf("Conversion failed. HTTP Code: %d\n%s", $converter->GetHTTPErrorCode(), $converter->GetLog()); } $doc->Close(); //-------------------------------------------------------------------------------- // Example 2) Modify the settings of the generated PDF pages and attach to an // existing PDF document. // open the existing PDF, and initialize the security handler $doc = new PDFDoc("../../TestFiles/numbered.pdf"); $doc->InitSecurityHandler(); // create the HTML2PDF converter object and modify the output of the PDF pages $converter = new HTML2PDF(); $converter->SetImageQuality(25); $converter->SetPaperSize(PrinterMode::e_11x17); // insert the web page to convert $converter->InsertFromURL($host . $page0); // convert the web page, appending generated PDF pages to doc if ($converter->Convert($doc)) { $doc->Save($output_path . "_02.pdf", SDFDoc::e_linearized); } else { echo printf("Conversion failed. HTTP Code: %d\n%s", $converter->GetHTTPErrorCode(), $converter->GetLog()); } $doc->Close(); //--------------------------------------------------------------------------------
$page_dict = $doc->GetTrailer()->Get("Root")->Value()->Get("Pages")->Value()->Get("Kids")->Value()->GetAt(0); // Embed a custom stream (file mystream.txt) using Flate compression. $embed_file = new StdFile($input_path . "my_stream.txt", StdFile::e_read_mode); $mystm = new FilterReader($embed_file); $page_dict->Put("Contents", $doc->CreateIndirectStream($mystm, new FlateEncode(new Filter()))); } //encrypt the document // Apply a new security handler with given security settings. // In order to open saved PDF you will need a user password 'test'. $new_handler = new SecurityHandler(); // Set a new password required to open a document $user_password = "******"; $new_handler->ChangeUserPassword($user_password); // Set Permissions $new_handler->SetPermission(SecurityHandler::e_print, true); $new_handler->SetPermission(SecurityHandler::e_extract_content, false); // Note: document takes the ownership of new_handler. $doc->SetSecurityHandler($new_handler); // Save the changes. echo nl2br("Saving modified file...\n"); $doc->Save($output_path . "secured.pdf", 0); $doc->Close(); // Example 2: // Opens an encrypted PDF document and removes its security. $doc = new PDFDoc($output_path . "secured.pdf"); //If the document is encrypted prompt for the password if (!$doc->InitSecurityHandler()) { echo nl2br("The password is: test\n"); echo nl2br("A password required to open the document.\n" . "Please enter the password:"******"UsrInput.html"; }
$tr3d->PushBackNumber(-1); $tr3d->PushBackNumber(0); $tr3d->PushBackNumber(1); $tr3d->PushBackNumber(0); $tr3d->PushBackNumber(0); $tr3d->PushBackNumber(-27.5); $tr3d->PushBackNumber(0); // Create annotation appearance stream, a thumbnail which is used during printing or // in PDF processors that do not understand 3D data. $ap_dict = $link_3D->PutDict("AP"); $builder = new ElementBuilder(); $writer = new ElementWriter(); $writer->Begin($doc->GetSDFDoc()); $thumb_pathname = $input_path . "dice.jpg"; $image = Image::Create($doc->GetSDFDoc(), $thumb_pathname); $writer->WritePlacedElement($builder->CreateImage($image, 0.0, 0.0, $link_3D_rect->Width(), $link_3D_rect->Height())); $normal_ap_stream = $writer->End(); $normal_ap_stream->PutName("Subtype", "Form"); $normal_ap_stream->PutRect("BBox", 0, 0, $link_3D_rect->Width(), $link_3D_rect->Height()); $ap_dict->Put("N", $normal_ap_stream); } // --------------------------------------------------------------------------------- PDFNet::Initialize(); $doc = new PDFDoc(); $page = $doc->PageCreate(); $doc->PagePushBack($page); $annots = $doc->CreateIndirectArray(); $page->GetSDFObj()->Put("Annots", $annots); Create3DAnnotation($doc, $annots); $doc->Save($output_path . "dice_u3d.pdf", SDFDoc::e_linearized); echo "Done.\n";
function CertifyPDF() { $infile = '../../TestFiles/newsletter.pdf'; $outfile = '../../TestFiles/Output/newsletter_certified.pdf'; $certfile = '../../TestFiles/pdftron.pfx'; $result = true; try { echo nl2br('Certifying PDF document: "' . $infile . '".' . PHP_EOL); // Open an existing PDF $doc = new PDFDoc($infile); // Add an StdSignatureHandler instance to PDFDoc, making sure to keep track of it using the ID returned. $sigHandlerId = $doc->AddStdSignatureHandler($certfile, "password"); // Create a new signature form field in the PDFDoc. $sigField = $doc->FieldCreate('Signature1', Field::e_signature); // Assign the form field as an annotation widget to the PDFDoc so that a signature appearance can be added. $page1 = $doc->GetPage(1); $widgetAnnot = Widget::Create($doc->GetSDFDoc(), new Rect(0.0, 0.0, 0.0, 0.0), $sigField); $page1->AnnotPushBack($widgetAnnot); $widgetAnnot->SetPage($page1); $widgetObj = $widgetAnnot->GetSDFObj(); $widgetObj->PutNumber('F', 132.0); $widgetObj->PutName('Type', 'Annot'); // Tell PDFNetC to use the SignatureHandler created to sign the new signature form field. $sigDict = $sigField->UseSignatureHandler($sigHandlerId); // Add more information to the signature dictionary. $sigDict->PutName('SubFilter', 'adbe.pkcs7.detached'); $sigDict->PutString('Name', 'PDFTron'); $sigDict->PutString('Location', 'Vancouver, BC'); $sigDict->PutString('Reason', 'Document verification.'); // Appearance can be added to the widget annotation. Please see the "SignPDF()" function for details. // Add this sigDict as DocMDP in Perms dictionary from root $root = $doc->GetRoot(); $perms = $root->PutDict('Perms'); // add the sigDict as DocMDP (indirect) in Perms $perms->Put('DocMDP', $sigDict); // add the additional DocMDP transform params $refObj = $sigDict->PutArray("Reference"); $transform = $refObj->PushBackDict(); $transform->PutName("TransformMethod", "DocMDP"); $transform->PutName("Type", "SigRef"); $transformParams = $transform->PutDict("TransformParams"); $transformParams->PutNumber("P", 1); // Set permissions as necessary. $transformParams->PutName("Type", "TransformParams"); $transformParams->PutName("V", "1.2"); // Save the PDFDoc. Once the method below is called, PDFNetC will also sign the document using the information // provided. $doc->Save($outfile, 0); echo nl2br('Finished certifying PDF document' . PHP_EOL); $doc->Close(); } catch (Exception $e) { echo nl2br($e->getMessage() . PHP_EOL); echo nl2br($e->getTraceAsString() . PHP_EOL); $result = false; } return $result; }
// Example 1) Update a business card template with personalized info $doc = new PDFDoc($input_path . "BusinessCardTemplate.pdf"); $doc->InitSecurityHandler(); // first, replace the image on the first page $replacer = new ContentReplacer(); $page = $doc->GetPage(1); $img = Image::Create($doc->GetSDFDoc(), $input_path . "peppers.jpg"); $replacer->AddImage($page->GetMediaBox(), $img->GetSDFObj()); // next, replace the text place holders on the second page $replacer->AddString("NAME", "John Smith"); $replacer->AddString("QUALIFICATIONS", "Philosophy Doctor"); $replacer->AddString("JOB_TITLE", "Software Developer"); $replacer->AddString("ADDRESS_LINE1", "#100 123 Software Rd"); $replacer->AddString("ADDRESS_LINE2", "Vancouver, BC"); $replacer->AddString("PHONE_OFFICE", "604-730-8989"); $replacer->AddString("PHONE_MOBILE", "604-765-4321"); $replacer->AddString("EMAIL", "*****@*****.**"); $replacer->AddString("WEBSITE_URL", "http://www.pdftron.com"); // finally, apply $replacer->Process($page); $doc->Save($output_path . "BusinessCard.pdf", 0); //-------------------------------------------------------------------------------- // Example 2) Replace text in a region with new text $doc = new PDFDoc($input_path . "newsletter.pdf"); $doc->InitSecurityHandler(); $replacer = new ContentReplacer(); $page = $doc->GetPage(1); $target_region = $page->GetMediaBox(); $replacer->AddText($target_region, "hello hello hello hello hello hello hello hello hello hello"); $replacer->Process($page); $doc->Save($output_path . "ContentReplaced.pdf", 0);
<?php //--------------------------------------------------------------------------------------- // Copyright (c) 2001-2014 by PDFTron Systems Inc. All Rights Reserved. // Consult LICENSE.txt regarding license information. //--------------------------------------------------------------------------------------- include "../../../PDFNetC/Lib/PDFNetPHP.php"; PDFNet::Initialize(); // Relative path to the folder containing the test files. $input_path = getcwd() . "/../../TestFiles/"; $output_path = $input_path . "Output/"; // Test - Adjust the position of content within the page. echo nl2br("_______________________________________________\n"); echo nl2br("Opening the input pdf...\n"); $input_doc = new PDFDoc($input_path . "tiger.pdf"); $input_doc->InitSecurityHandler(); $pg_itr1 = $input_doc->GetPageIterator(); $media_box = new Rect($pg_itr1->Current()->GetMediaBox()); $media_box->x1 -= 200; $media_box->x2 -= 200; $media_box->Update(); $input_doc->Save($output_path . "tiger_shift.pdf", 0); $input_doc->Close(); echo nl2br("Done. Result saved in tiger_shift...\n");
// Example 3) Use monochrome image settings and default settings // for color and grayscale images. $doc = new PDFDoc($input_path . $input_filename . ".pdf"); $doc->InitSecurityHandler(); $mono_image_settings = new MonoImageSettings(); $mono_image_settings->SetCompressionMode(MonoImageSettings::e_jbig2); $mono_image_settings->ForceRecompression(true); $opt_settings = new OptimizerSettings(); $opt_settings->SetMonoImageSettings($mono_image_settings); Optimizer::Optimize($doc, $opt_settings); $doc->Save($output_path . $input_filename . "_opt3.pdf", SDFDoc::e_linearized); $doc->Close(); // ---------------------------------------------------------------------- // Example 4) Use Flattener to simplify content in this document // using default settings $doc = new PDFDoc($input_path . "TigerText.pdf"); $doc->InitSecurityHandler(); $fl = new Flattener(); // The following lines can increase the resolution of background // images. //$fl->SetDPI(300); //$fl->SetMaximumImagePixels(5000000); // This line can be used to output Flate compressed background // images rather than DCTDecode compressed images which is the default //$fl->SetPreferJPG(false); // In order to adjust thresholds for when text is Flattened // the following function can be used. //$fl->SetThreshold(Flattener::e_threshold_keep_most); // We use e_fast option here since it is usually preferable // to avoid Flattening simple pages in terms of size and // rendering speed. If the desire is to simplify the
// Consult LICENSE.txt regarding license information. //--------------------------------------------------------------------------------------- include "../../../PDFNetC/Lib/PDFNetPHP.php"; //----------------------------------------------------------------------------------- // This sample illustrates how to embed various raster image formats // (e.g. TIFF, JPEG, JPEG2000, JBIG2, GIF, PNG, BMP, etc.) in a PDF document. // // Note: On Windows platform this sample utilizes GDI+ and requires GDIPLUS.DLL to // be present in the system path. //----------------------------------------------------------------------------------- PDFNet::Initialize(); // Relative path to the folder containing the test files. $input_path = getcwd() . "/../../TestFiles/"; $output_path = $input_path . "Output/"; echo nl2br("-------------------------------------------------\n"); $doc = new PDFDoc(); $builder = new ElementBuilder(); // Used to build new Element objects $writer = new ElementWriter(); // Used to write Elements to the page $page = $doc->PageCreate(); // Start a new page $writer->Begin($page); // Begin writing to this page // ---------------------------------------------------------- // Add JPEG image to the output file $img = Image::Create($doc->GetSDFDoc(), $input_path . "peppers.jpg"); $element = $builder->CreateImage($img, 50.0, 500.0, (double) $img->GetImageWidth() / 2, (double) $img->GetImageHeight() / 2); $writer->WritePlacedElement($element); // ---------------------------------------------------------- // Add a PNG image to the output file
$input_path = getcwd() . "/../../TestFiles/"; $output_path = $input_path . "Output/"; // The following sample illustrates how to read/write a PDF document from/to // a memory buffer. This is useful for applications that work with dynamic PDF // documents that don't need to be saved/read from a disk. PDFNet::Initialize(); // Read a PDF document in a memory buffer. $file = new MappedFile($input_path . "tiger.pdf"); $file_sz = $file->FileSize(); $file_reader = new FilterReader($file); $mem = $file_reader->Read($file_sz); $test = array(); for ($i = 0; $i < strlen($mem); $i++) { $test[] = ord($mem[$i]); } $doc = new PDFDoc($mem, $file_sz); $doc->InitSecurityHandler(); $num_pages = $doc->GetPageCount(); $writer = new ElementWriter(); $reader = new ElementReader(); // Create a duplicate of every page but copy only path objects for ($i = 1; $i <= $num_pages; ++$i) { $itr = $doc->GetPageIterator(2 * $i - 1); $reader->Begin($itr->Current()); $new_page = $doc->PageCreate($itr->Current()->GetMediaBox()); $next_page = $itr; $next_page->Next(); $doc->PageInsert($next_page, $new_page); $writer->Begin($new_page); while (($element = $reader->Next()) != null) { //if ($element->GetType() == Element::e_path)
* * Following this function is the more complex way of using PDFDraw directly. * * The first example uses the new PDF::Print::StartPrintJob function to send a rasterization * of the document with optimal compression to the printer. If the OS is Windows 7, then the * XPS print path will be used to preserve vector quality. * * The second example uses PDFDraw send unoptimized rasterized data via the GDI print path. * * If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you * should use PDFRasterizer or PDFNet vector output instead of PDFDraw. */ PDFNet::Initialize(); // Relative path to the folder containing test files. $input_path = getcwd() . "/../../TestFiles/"; $doc = new PDFDoc($input_path . "tiger.pdf"); $doc->InitSecurityHandler(); // Set our PrinterMode options $printerMode = new PrinterMode(); $printerMode->SetCollation(true); $printerMode->SetCopyCount(1); $printerMode->SetDPI(600); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting $printerMode->SetDuplexing(PrinterMode::e_Duplex_Auto); // If the XPS print path is being used, then the printer spooler file will // ignore the grayscale option and be in full color $printerMode->SetOutputColor(PrinterMode::e_OutputColor_Grayscale); $printerMode->SetOutputQuality(PrinterMode::e_OutputQuality_Medium); // $printerMode->SetNUp(2,1); // $printerMode->SetScaleType(PrinterMode::e_ScaleType_FitToOutputPage); // Print the PDF document to the default printer, using "tiger.pdf" as the document
// prior to printing or to assemble a 'master' page from several 'source' // pages. Using PDFNet API it is possible to write applications that can // re-order the pages such that they will display in the correct order // when the hard copy pages are compiled and folded correctly. //----------------------------------------------------------------------------------- PDFNet::Initialize(); echo nl2br("-------------------------------------------------\n"); echo nl2br("Opening the input pdf...\n"); $in_doc = new PDFDoc($input_path . "newsletter.pdf"); $in_doc->InitSecurityHandler(); // Create a list of pages to import from one PDF document to another. $import_pages = new VectorPage(); for ($itr = $in_doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) { $import_pages->push($itr->Current()); } $new_doc = new PDFDoc(); $imported_pages = $new_doc->ImportPages($import_pages); // Paper dimension for A3 format in points. Because one inch has // 72 points, 11.69 inch 72 = 841.69 points $media_box = new Rect(0.0, 0.0, 1190.88, 841.6900000000001); $mid_point = $media_box->Width() / 2; $builder = new ElementBuilder(); $writer = new ElementWriter(); for ($i = 0; $i < $imported_pages->size(); ++$i) { // Create a blank new A3 page and place on it two pages from the input document. $new_page = $new_doc->PageCreate($media_box); $writer->Begin($new_page); // Place the first page $src_page = $imported_pages->get($i); $element = $builder->CreateForm($src_page); $sc_x = $mid_point / $src_page->GetPageWidth();
if (array_key_exists($cont->GetMCID(), $mcid_page_map)) { echo $mcid_page_map[$cont->GetMCID()]; } } } } else { // the kid is another StructElement node. ProcessStructElement2($element->GetAsStructElem($i), $mcid_doc_map, $ident + 1); } } PrintIdent($ident); echo "</" . $element->GetType() . ">"; } PDFNet::Initialize(); // Extract logical structure from a PDF document $doc = new PDFDoc($input_path . "tagged.pdf"); $doc->InitSecurityHandler(); echo nl2br("____________________________________________________________\n"); echo nl2br("Sample 1 - Traverse logical structure tree...\n"); $tree = $doc->GetStructTree(); if ($tree->IsValid()) { echo nl2br("Document has a StructTree root.\n"); for ($i = 0; $i < $tree->GetNumKids(); ++$i) { // Recursively get structure info for all child elements. ProcessStructElement($tree->GetKid($i), 0); } } else { echo nl2br("This document does not contain any logical structure.\n"); } echo nl2br("\nDone 1.\n"); echo nl2br("____________________________________________________________\n");
// The following example illustrates how to traverse the outline tree using // Bookmark navigation methods: Bookmark.GetNext(), Bookmark.GetPrev(), // Bookmark.GetFirstChild () and Bookmark.GetLastChild (). // Open the document that was saved in the previous code sample $doc = new PDFDoc($output_path . "bookmark.pdf"); $doc->InitSecurityHandler(); $root = $doc->GetFirstBookmark(); PrintOutlineTree($root); echo "Done."; // The following example illustrates how to create a Bookmark to a page // in a remote document. A remote go-to action is similar to an ordinary // go-to action, but jumps to a destination in another PDF file instead // of the current file. See Section 8.5.3 'Remote Go-To Actions' in PDF // Reference Manual for details. // Open the document that was saved in the previous code sample $doc = new PDFDoc($output_path . "bookmark.pdf"); $doc->InitSecurityHandler(); // Create file specification (the file referred to by the remote bookmark) $file_spec = $doc->CreateIndirectDict(); $file_spec->PutName("Type", "Filespec"); $file_spec->PutString("F", "bookmark.pdf"); $spec = new FileSpec($file_spec); $goto_remote = Action::CreateGotoRemote($spec, 5, true); $remoteBookmark1 = Bookmark::Create($doc, "REMOTE BOOKMARK 1"); $remoteBookmark1->SetAction($goto_remote); $doc->AddRootBookmark($remoteBookmark1); // Create another remote bookmark, but this time using the low-level SDF/Cos API. // Create a remote action $remoteBookmark2 = Bookmark::Create($doc, "REMOTE BOOKMARK 2"); $doc->AddRootBookmark($remoteBookmark2); $gotoR = $remoteBookmark2->GetSDFObj()->PutDict("A");
} echo nl2br("</Line>\n"); } if ($cur_flow_id != -1) { if ($cur_para_id != -1) { $cur_para_id = -1; echo nl2br("</Para>\n"); } echo nl2br("</Flow>\n"); } $txt->Destroy(); $doc->Close(); echo nl2br("-----------------------------------------------------------\n"); } if ($example5_low_level) { $doc = new PDFDoc($input_path); $doc->InitSecurityHandler(); // Example 1. Extract all text content from the document $reader = new ElementReader(); // Read every page for ($itr = $doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) { $reader->Begin($itr->Current()); DumpAllText($reader); $reader->End(); } // Example 2. Extract text content based on the // selection rectangle. echo nl2br("\n----------------------------------------------------"); echo nl2br("\nExtract text based on the selection rectangle."); echo nl2br("\n----------------------------------------------------\n"); $first_page = $doc->GetPage(1);
$doc->InitSecurityHandler(); $s = new Stamper(Stamper::e_relative_scale, 0.05, 0.05); $s->SetPosition(0.0, 0.0); $s->SetOpacity(0.7); $s->SetRotation(90); $s->SetSize(Stamper::e_font_size, 80, -1); $s->SetTextAlignment(Stamper::e_align_center); $ps = new PageSet(1, 20, PageSet::e_even); $s->StampText($doc, "Goodbye\nMoon", $ps); $doc->Save($output_path . $input_filename . ".ex5.pdf", SDFDoc::e_linearized); $doc->Close(); //-------------------------------------------------------------------------------- // Example 6) Add first page as stamp to all even pages $doc = new PDFDoc($input_path . $input_filename); $doc->InitSecurityHandler(); $fish_doc = new PDFDoc($input_path . "fish.pdf"); $fish_doc->InitSecurityHandler(); $s = new Stamper(Stamper::e_relative_scale, 0.3, 0.3); $s->SetOpacity(1); $s->SetRotation(270); $s->SetAsBackground(true); $s->SetPosition(0.5, 0.5, true); $s->SetAlignment(Stamper::e_horizontal_left, Stamper::e_vertical_bottom); $page_one = $fish_doc->GetPage(1); $ps = new PageSet(1, $doc->GetPageCount(), PageSet::e_even); $s->StampPage($doc, $page_one, $ps); $doc->Save($output_path . $input_filename . ".ex6.pdf", SDFDoc::e_linearized); $doc->Close(); //-------------------------------------------------------------------------------- // Example 7) Add image stamp at top right corner in every pages $doc = new PDFDoc($input_path . $input_filename);
if ($ipage == 0) { //$page7->AnnotPushBack( $st ); } else { $page8->AnnotPushBack($st); $st->RefreshAppearance(); } } } $st = RubberStamp::Create($doc->GetSDFDoc(), new Rect(400.0, 5.0, 550.0, 45.0)); $st->SetIcon("UserStamp"); $st->SetContents("User defined stamp"); $page8->AnnotPushBack($st); $st->RefreshAppearance(); } PDFNet::Initialize(); $doc = new PDFDoc($input_path . "numbered.pdf"); $doc->InitSecurityHandler(); // An example of using SDF/Cos API to add any type of annotations. AnnotationLowLevelAPI($doc); $doc->Save($output_path . "annotation_test1.pdf", SDFDoc::e_remove_unused); // An example of using the high-level PDFNet API to read existing annotations, // to edit existing annotations, and to create new annotation from scratch. AnnotationHighLevelAPI($doc); $doc->Save($output_path . "annotation_test2.pdf", SDFDoc::e_linearized); // an example of creating various annotations in a brand new document $doc1 = new PDFDoc(); CreateTestAnnots($doc1); $outfname = $output_path . "new_annot_test_api.pdf"; $doc1->Save($outfname, SDFDoc::e_linearized); echo nl2br("Saved " . $outfname . "\n"); $doc->Close();
$reader->FormBegin(); ProcessElements($reader); $reader->End(); break; case Element::e_image: ProcessImage($element); break; } } } # Relative path to the folder containing the test files. $input_path = getcwd() . "/../../TestFiles/"; $output_path = $input_path . "Output/"; PDFNet::Initialize(); # Extract text data from all pages in the document echo nl2br("__________________________________________________\n"); echo nl2br("Extract page element information from all \n"); echo nl2br("pages in the document.\n"); $doc = new PDFDoc($input_path . "newsletter.pdf"); $doc->InitSecurityHandler(); $pgnum = $doc->GetPageCount(); $page_begin = $doc->GetPageIterator(); $page_reader = new ElementReader(); for ($itr = $page_begin; $itr->HasNext(); $itr->Next()) { echo nl2br("Page " . $itr->Current()->GetIndex() . "----------------------------------------\n"); $page_reader->Begin($itr->Current()); ProcessElements($page_reader); $page_reader->End(); } $doc->Close(); echo nl2br("Done.\n");
// Replace the Prefix in the decimal labels (from example 1). $label = $doc->GetPageLabel(4); if ($label->IsValid()) { $label->SetPrefix("A"); $label->SetStart(1); } // Add a new label $new_label = PageLabel::Create($doc->GetSDFDoc(), PageLabel::e_decimal, "B", 1); $doc->SetPageLabel(10, $new_label); // starting from page 10. $doc->Save($output_path . "newsletter_with_pagelabels_modified.pdf", SDFDoc::e_linearized); echo nl2br("Done. Result saved in newsletter_with_pagelabels_modified.pdf...\n"); $page_num = $doc->GetPageCount(); for ($i = 1; $i <= $page_num; ++$i) { echo "Page number: " . $i; $label = $doc->GetPageLabel($i); if ($label->IsValid()) { echo nl2br(" Label: " . $label->GetLabelTitle($i) . "\n"); } else { echo nl2br(" No Label.\n"); } } $doc->Close(); //----------------------------------------------------------- // Example 4: Delete all page labels in an existing PDF document. //----------------------------------------------------------- $doc = new PDFDoc($output_path . "newsletter_with_pagelabels.pdf"); $doc->GetRoot()->Erase("PageLabels"); $doc->Save($output_path . "newsletter_with_pagelabels_removed.pdf", SDFDoc::e_linearized); echo nl2br("Done. Result saved in newsletter_with_pagelabels_removed.pdf...\n"); // ...
$new_handler = new SecurityHandler(); // Set a new password required to open a document $user_password = "******"; $new_handler->ChangeUserPassword($user_password); // Set Permissions $new_handler->SetPermission(SecurityHandler::e_print, true); $new_handler->SetPermission(SecurityHandler::e_extract_content, false); // Note: document takes the ownership of new_handler. $doc->SetSecurityHandler($new_handler); // Save the changes. echo "Saving modified file...\n"; $doc->Save($output_path . "secured.pdf", 0); $doc->Close(); // Example 2: // Opens an encrypted PDF document and removes its security. $doc = new PDFDoc($output_path . "secured.pdf"); //If the document is encrypted prompt for the password if (!$doc->InitSecurityHandler()) { $success = false; echo "The password is: test\n"; for ($count = 0; $count < 3; $count++) { echo "A password required to open the document.\n" . "Please enter the password:"******"The password is correct.\n"; break; } else { if ($count < 3) { echo "The password is incorrect, please try again\n"; }
$zoom_rect = new Rect(216.0, 522.0, 330.0, 600.0); $page->SetCropBox($zoom_rect); // Set the page crop box. // Select the crop region to be used for drawing. $draw->SetPageBox(Page::e_crop); $draw->SetDPI(900); // Set the output image resolution to 900 DPI. $draw->Export($page, $output_path . "tiger_zoom_900dpi.png", "PNG"); echo nl2br("Example 5: " . $output_path . "tiger_zoom_900dpi.png. Done.\n"); $draw->SetImageSize(50, 50); // Set the thumbnail to be 50x50 pixel image. $draw->Export($page, $output_path . "tiger_zoom_50x50.png", "PNG"); echo nl2br("Example 5: " . $output_path . "tiger_zoom_50x50.png. Done.\n"); $cmyk_hint = $hint_set->CreateDict(); $cmyk_hint->PutName("ColorSpace", "CMYK"); //-------------------------------------------------------------------------------- // Example 6) Convert the first PDF page to CMYK TIFF at 92 DPI. // A three step tutorial to convert PDF page to an image echo nl2br("Example 6:\n"); // A) Open the PDF document. $doc = new PDFDoc($input_path . "tiger.pdf"); // Initialize the security handler, in case the PDF is encrypted. $doc->InitSecurityHandler(); // B) The output resolution is set to 92 DPI. $draw->SetDPI(92); // C) Rasterize the first page in the document and save the result as TIFF. $pg = $doc->GetPage(1); $draw->Export($pg, $output_path . "out1.tif", "TIFF", $cmyk_hint); echo nl2br("Example 6: Result saved in " . $output_path . "out1.tif\n"); $doc->Close(); echo "Done.";
case Element::e_form: $o = $element->GetXObject(); $objNum = $o->GetObjNum(); $map[$objNum] = $o; $writer->WriteElement($element); break; default: $writer->WriteElement($element); } } } PDFNet::Initialize(); echo nl2br("-------------------------------------------------\n"); // Open the test file echo nl2br("Opening the input file...\n"); $doc = new PDFDoc($input_path . $input_filename); $doc->InitSecurityHandler(); $writer = new ElementWriter(); $reader = new ElementReader(); $itr = $doc->GetPageIterator(); while ($itr->HasNext()) { $page = $itr->Current(); $reader->Begin($page); $writer->Begin($page, ElementWriter::e_replacement, false); $map1 = array(); ProcessElements($reader, $writer, $map1); $writer->End(); $reader->End(); $map2 = array(); while (!(empty($map1) && empty($map2))) { foreach ($map1 as $k => $v) {