Ejemplo n.º 1
1
 public function getPdfContent($name, array $data = array())
 {
     $this->init();
     $tplFile = sprintf('%s:%s.pdf.twig', $this->options['tplShortDirectory'], $name);
     $htmlContent = $this->twig->render($tplFile, $data);
     $pdfContent = $this->snappy->getOutputFromHtml($htmlContent);
     return $pdfContent;
 }
<?php

require_once 'vendor/autoload.php';
use Knp\Snappy\Pdf;
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
// Cabeçalho para o navegador entender que o conteúdo é um PDF
header('Content-Type: application/pdf');
// Se quiser forçar o download, descomente a linha abaixo e
// modifica o valor do parâmetro filename para o valor desejado
//header('Content-Disposition: attachment; filename="schoolofnet-blog-artigos.pdf"');
echo $snappy->getOutput(array('http://www.schoolofnet.com/2015/07/trabalhando-com-repository-no-laravel/', 'http://www.schoolofnet.com/2015/04/como-usar-os-metodos-magicos-no-php/', 'http://www.schoolofnet.com/2015/04/enviando-emails-utilizando-swift-mailer/', 'http://www.schoolofnet.com/2015/04/instalando-e-integrando-apache-com-php-no-windows/'));
// Se quiser salvar numa pasta do servidor ao invés mostrar no navegador,
// comente a linha do getOutput(),
// descomente a linha abaixo e arrume o segundo parâmetro.
//$snappy->generate(
//    [
//        'http://www.schoolofnet.com/2015/07/trabalhando-com-repository-no-laravel/',
//        'http://www.schoolofnet.com/2015/04/como-usar-os-metodos-magicos-no-php/',
//        'http://www.schoolofnet.com/2015/04/enviando-emails-utilizando-swift-mailer/',
//        'http://www.schoolofnet.com/2015/04/instalando-e-integrando-apache-com-php-no-windows/',
//    ],
//    '/app/arquivos/son/artigos.pdf'
//);
Ejemplo n.º 3
0
 public function rootAction(Application $app, Request $request)
 {
     $data = $this->prepareInput();
     if ($data === null) {
         return new JsonResponse(['error' => 'no json data found'], 400);
     }
     $templateName = isset($data['template']) ? $data['template'] : null;
     $templateData = isset($data['data']) ? $data['data'] : null;
     if (!$templateName || !$templateData) {
         return new JsonResponse(['error' => 'template and data must be set'], 400);
     }
     $repo = $app->getTemplateRepository();
     $template = $repo->getByName($templateName);
     if (!$template) {
         return new JsonResponse(['error' => "template {$templateName} not found"], 404);
     }
     $twig = new \Twig_Environment(new \Twig_Loader_String());
     $html = $twig->render($template->getTemplate(), $templateData);
     $file = new File();
     $file->setId(Uuid::uuid4()->toString());
     $file->setCreatedAt(date('Y-m-d H:i:s'));
     $file->setPath($this->getFilePath($file));
     $snappy = new Pdf();
     if (substr(php_uname(), 0, 7) == "Windows") {
         $snappy->setBinary('vendor\\bin\\wkhtmltopdf.exe.bat');
     } else {
         $snappy->setBinary('vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');
     }
     $snappy->generateFromHtml($html, $file->getPath());
     $repo = $app->getFileRepository();
     $repo->add($file);
     return new JsonResponse(['id' => $file->getId()], 201);
 }
 public function test()
 {
     $bin = BASE_PATH . 'vendor/bin/wkhtmltopdf-amd64';
     // Display the resulting pdf in the browser
     // by setting the Content-type header to pdf
     $snappy = new Pdf();
     $snappy->setBinary($bin);
     $snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', BASE_PATH . 'storage/bill-123.pdf');
 }
Ejemplo n.º 5
0
 public function doGetIt(SS_HTTPRequest $request)
 {
     // var_dump($request->params());
     global $baseDir;
     $result = $this->getMovieList()->byId($request->param('ID'));
     printf($result->ID);
     $filePath = $baseDir . '/pdfs/movie-' . $result->ID . '.pdf';
     $pdf_creator = new Pdf($baseDir . '\\vendor\\bin\\wkhtmltopdf');
     return $pdf_creator->generateFromHtml($result->renderWith('SingleMovie'), $filePath, array('disable-javascript' => false), true);
 }
Ejemplo n.º 6
0
 public function doGetPdf($data, $form)
 {
     global $baseDir;
     $website = $data['Website'];
     $pdf_creator = new Pdf($baseDir . '\\vendor\\bin\\wkhtmltopdf');
     header('Content-Type: application/pdf');
     header('Content-Disposition: inline; filename="file.pdf"');
     echo $pdf_creator->getOutput($website);
     return $this->redirectBack();
 }
Ejemplo n.º 7
0
 /**
  * Save the PDF to a file
  *
  * @param $filename
  * @return static
  */
 public function save($filename)
 {
     if ($this->html) {
         $this->snappy->generateFromHtml($this->html, $filename, $this->options);
     } elseif ($this->file) {
         $this->snappy->generate($this->file, $filename, $this->options);
     }
     return $this;
 }
Ejemplo n.º 8
0
 public function __construct($path = null, array $options = [])
 {
     if (!$path) {
         if (!($path = static::$path)) {
             # Check which version we should use based on the current machine architecture
             $bin = "wkhtmltopdf-";
             if (posix_uname()["machine"][0] == "i") {
                 $bin .= "i386";
             } else {
                 $bin .= "amd64";
             }
             # Start in the directory that we are in
             $path = __DIR__;
             # Move up to the composer vendor directory
             $path .= "/../../..";
             # Add the wkhtmltopdf binary path
             $path .= "/h4cc/" . $bin . "/bin/" . $bin;
             static::$path = $path;
         }
     }
     parent::__construct($path, $options);
 }
Ejemplo n.º 9
0
<?php

use Knp\Snappy\Pdf;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Seld\JsonLint\JsonParser;
use Symfony\Component\PropertyAccess\PropertyAccess;
//Request::setTrustedProxies(array('127.0.0.1'));
$app->post('/', function (Request $request) use($app) {
    $parser = new JsonParser();
    $accessor = PropertyAccess::createPropertyAccessor();
    $snappy = new Pdf();
    $snappy->setBinary($app['wkhtmltopdf.binary']);
    $parameters = $parser->parse($request->getContent());
    if ($accessor->isReadable($parameters, 'options')) {
        foreach ((array) $accessor->getValue($parameters, 'options') as $name => $value) {
            $snappy->setOption($name, $value);
        }
    }
    $app['tmpFile'] = sys_get_temp_dir() . '/' . md5($request->getContent());
    if ($accessor->isReadable($parameters, 'source.url')) {
        $dns = new Net_DNS2_Resolver();
        $dns->query(parse_url($accessor->getValue($parameters, 'source.url'), PHP_URL_HOST));
        $snappy->generate($accessor->getValue($parameters, 'source.url'), $app['tmpFile'], [], true);
    } elseif ($accessor->isReadable($parameters, 'source.html')) {
        $snappy->generateFromHtml($accessor->getValue($parameters, 'source.html'), $app['tmpFile'], [], true);
    } elseif ($accessor->isReadable($parameters, 'source.base64')) {
        $snappy->generateFromHtml(base64_decode($accessor->getValue($parameters, 'source.base64')), $app['tmpFile'], [], true);
    }
    return new BinaryFileResponse($app['tmpFile']);
Ejemplo n.º 10
0
<?php

require_once 'vendor/knplabs/knp-snappy/src/autoload.php';
use Knp\Snappy\Pdf;
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->setOption('disable-javascript', true);
$snappy->setOption('disable-local-file-access', true);
$snappy->setOption('orientation', 'Landscape');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="My NUSMods.com Timetable.pdf"');
echo $snappy->getOutputFromHtml(urldecode($_POST['html']));
Ejemplo n.º 11
0
 public function taskToPDF(Request $request, Task $task)
 {
     //        $binary = base_path().'/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64';
     $binary = '/usr/bin/xvfb-run /usr/bin/wkhtmltopdf';
     $snappy = new Pdf($binary);
     //$html = file_get_contents('http://www.google.com');
     $pdf = base_path() . '/storage/app/pdfs/task_id' . $task->id . '.pdf';
     $snappy->generateFromHtml('<h1>' . $task->name . '</h1><p>' . $task->user->name . '</p>', $pdf, array(), true);
     return response()->download($pdf, 'task.pdf', ['Content-Type' => 'application/pdf']);
     // or you can do it in two steps
     //        $snappy = new Pdf();
     //        $snappy->setBinary($binary);
     //// Display the resulting pdf in the browser
     //// by setting the Content-type header to pdf
     //        //$snappy = new Pdf($binary);
     //        header('Content-Type: application/pdf');
     //        header('Content-Disposition: attachment; filename="file.pdf"');
     //        echo $snappy->getOutput('http://www.github.com');
     //
     //// Merge multiple urls into one pdf
     //// by sending an array of urls to getOutput()
     //        $snappy = new Pdf($binary);
     //        header('Content-Type: application/pdf');
     //        header('Content-Disposition: attachment; filename="file.pdf"');
     //        echo $snappy->getOutput(array('http://www.github.com','http://www.knplabs.com','http://www.php.net'));
     //
     //// .. or simply save the PDF to a file
     //        $snappy = new Pdf($binary);
     //        $snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', base_path().'/resources/bill-123.pdf');
     //        return response();
     //
     //// Pass options to snappy
     //// Type wkhtmltopdf -H to see the list of options
     //        $snappy = new Pdf($binary);
     //        $snappy->setOption('disable-javascript', true);
     //        $snappy->setOption('no-background', true);
     //        $snappy->setOption('allow', array('/path1', '/path2'));
     //        $snappy->setOption('cookie', array('key' => 'value', 'key2' => 'value2'));
     //        $snappy->setOption('cover', 'pathToCover.html');
     //// .. or pass a cover as html
     //        $snappy->setOption('cover', '<h1>Bill cover</h1>');
     //        $snappy->setOption('toc', true);
     //        $snappy->setOption('cache-dir', '/path/to/cache/dir');
 }
Ejemplo n.º 12
0
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
use Illuminate\Http\Request;
use Knp\Snappy\Pdf;
$app->get('/', function () use($app) {
    echo "Make a post request to either /html or /url";
});
$app->get('/html', function () use($app) {
    echo "Use post with a base64 encoded html parameter";
});
$app->post('/html', function (Request $request) use($app) {
    $pdf = new Pdf('xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf');
    echo base64_encode($pdf->getOutputFromHtml(base64_decode(file_get_contents('php://input'))));
});
$app->get('/url', function () use($app) {
    echo "Use post with a url parameter";
});
$app->post('/url', function (Request $request) use($app) {
    $pdf = new Pdf('xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf');
    echo base64_encode($pdf->getOutput($request->get('url')));
});
<?php

require_once 'vendor/autoload.php';
use Knp\Snappy\Pdf;
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
// Cabeçalho para o navegador entender que o conteúdo é um PDF
header('Content-Type: application/pdf');
// Se quiser forçar o download, descomente a linha abaixo e
// modifica o valor do parâmetro filename para o valor desejado
//header('Content-Disposition: attachment; filename="relatorio.pdf"');
$html = <<<'EOD'
<h1 style="color: red;">Relatório</h1>
<br/>
<table width="100%">
    <thead>
        <tr>
            <th>Nome</th>
            <th>E-mail</th>
            <th>Telefone</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Fulano da Silva</td>
            <td>fulano@dasilva.com</td>
            <td>11 99999-8888</td>
        </tr>
        <tr>
            <td>Sicrano Santos</td>
            <td>sicrano@gmail.com</td>
            <td>11 99999-7777</td>
Ejemplo n.º 14
0
 /**
  * @param $orderUid
  * @return string
  * @throws \Exception
  */
 protected function generatePdfReceipt($orderUid)
 {
     $snappy = new Pdf($this->pixie->config->get('parameters.wkhtmltopdf_path'));
     //$snappy->setOption('cookie', $_COOKIE);
     $snappy->setOption('viewport-size', '800x600');
     $snappy->setOption('toc', false);
     $snappy->setOption('outline', false);
     $snappy->setOption('outline-depth', 0);
     $url = ($_SERVER['HTTPS'] == 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/payment/request_bill/' . $orderUid . '?print=1' . '&code=' . $this->generatePrintCode($orderUid);
     return $snappy->getOutput($url);
 }
Ejemplo n.º 15
0
 private function creerdevispdf($id)
 {
     $em = $this->getDoctrine()->getManager();
     $devis = $em->getRepository('AcmeProsalesBundle:Devis')->find($id);
     $parametrepaiement = $em->getRepository('AcmeProsalesBundle:Parametres')->findOneBy(array('nom' => 'paiement'));
     $nomfichier = "Devis_" . $devis->getReference() . '.pdf';
     //        $nomfichier = "Devis".$id.'.pdf';
     $outputfile = $this->getUploadRootDir() . '/' . $nomfichier;
     if (!$devis) {
         throw $this->createNotFoundException('Impossible de trouver le devis recherché.');
     }
     $html = $this->renderView('AcmeProsalesBundle:Devis:imprimer.html.twig', array('entity' => $devis, 'paiement' => $parametrepaiement));
     if (file_exists($outputfile)) {
         unlink($outputfile);
     }
     //        $this->get('knp_snappy.pdf')->generateFromHtml($html,$outputfile);
     //        return $outputfile;
     $snappy = new Pdf($this->getWebDir() . '../vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386');
     //        $snappy->setOption('disable-javascript', true);
     $snappy->setOption('outline', true);
     $snappy->setOption('background', true);
     //        $snappy->setOption('margin-top', '15mm');
     //        $snappy->setOption('margin-bottom', '15mm');
     //        $snappy->setOption('header-center', 'ceci et l\'entête');
     $snappy->setOption('header-right', '[page]/[toPage]');
     $snappy->setOption('header-left', '[date]');
     $snappy->setOption('header-line', true);
     //$snappy->setOption('header-font-size', '18');
     $snappy->setOption('footer-center', '20 Allée des Erables Bat D- Bp64162 - 95978 Roissy CDG Cedex  FRANCE<br>Info@progiss.com - www.progiss.com - Tel 01 49 89 07 90 - Fax 01 49 89 07 91<br>SAS au capital de 43750 Euros  - Siret :49901977600024 R.C.S Bobigny N° TVA : FR43499019776');
     //        $snappy->setOption('footer-right', '[page]/[toPage]');
     $snappy->setOption('footer-line', true);
     //        $snappy->setOption('no-footer-line', true);
     $snappy->setOption('footer-font-size', '6');
     //$snappy->setOption('no-background', true);
     //$snappy->setOption('allow', array('/path1', '/path2'));
     //$snappy->setOption('cookie', array('key' => 'value', 'key2' => 'value2'));
     $snappy->generateFromHtml($html, $outputfile);
     return $outputfile;
 }
Ejemplo n.º 16
0
 /**
  * @param \Illuminate\Filesystem\Filesystem
  * @param string $binary
  * @param array $options
  */
 public function __construct(Filesystem $fs, $binary, array $options, array $env)
 {
     parent::__construct($binary, $options, $env);
     $this->fs = $fs;
 }
Ejemplo n.º 17
0
 public function uploadMdFile(Request $request)
 {
     $file = $request->file('file');
     $mdText = file_get_contents($file->getPathName());
     $data = $request->all();
     $cssData = $data['css_data'];
     $disabledCss = $data['css_disabled'];
     //echo $file->getFileName(); // tmp file name
     // Markdown をhtmlに変換
     $parsedown = new Parsedown();
     $body = $parsedown->text($mdText);
     // html全体を生成
     //$html = $this->_createHtml($body);
     $html = $this->_createHtml($body, $cssData, $disabledCss);
     // PDFの作成
     $snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
     // filename
     $pdfName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . "_" . date("YmdHis") . ".pdf";
     $snappy->generateFromHtml($html, storage_path() . "/app/pdf/{$pdfName}");
     return response()->json(array("name" => $pdfName));
 }
Ejemplo n.º 18
0
 protected function _generate()
 {
     $snappy = new Pdf($this->binLocation);
     $this->content = $snappy->getOutputFromHtml($this->content);
 }
Ejemplo n.º 19
0
 public function saveDocument($data)
 {
     $this->load->helper('file');
     $docNameNew = uniqid('', true);
     $docName = $docNameNew . '.php';
     //add slashes to file path
     $path = addslashes(FCPATH);
     $header = '<?php include("' . $path . $this->config->item('dataDir') . 'includes/header.php"); ?>';
     $footer = '<?php include("' . $path . $this->config->item('dataDir') . 'includes/footer.php"); ?>';
     if (!write_file($this->config->item('dataDir') . $docName, $header, 'w')) {
         $msg = array('status' => 'error', 'msg' => 'There was an error writing the new document to a file.');
         echo json_encode($msg);
         exit;
     }
     foreach ($data['modules'] as $module) {
         $modData = new Module_Model($module);
         $location = $modData->getLocation();
         $cat = $modData->getCategory();
         //make sure we can load the module data successfully before creating a bogus file
         if ($location != '' && $cat != '') {
             $innerHtml = '<?php include("' . $path . $this->config->item('moduleDir') . $cat . '/files/' . $location . '") ?>';
             if (!write_file($this->config->item('dataDir') . $docName, $innerHtml, 'a')) {
                 $msg = array('status' => 'error', 'msg' => 'There was an error writing the new document to a file.');
                 echo json_encode($msg);
                 exit;
             }
         } else {
             $msg = array('status' => 'error', 'msg' => 'There was an error loading the modules location and category information.');
             echo json_encode($msg);
             exit;
         }
     }
     if (!write_file($this->config->item('dataDir') . $docName, $footer, 'a')) {
         $msg = array('status' => 'error', 'msg' => 'There was an error writing the new document to a file.');
         echo json_encode($msg);
         exit;
     }
     $pdf = new Pdf($this->config->item('pdf_binary'));
     $image = new Image($this->config->item('image_binary'));
     $options = array('format' => 'jpg', 'user-style-sheet' => FCPATH . 'assets/css/bootstrap.css', 'load-error-handling' => 'skip');
     $html = $this->load->file(FCPATH . $this->config->item('dataDir') . $docName, true);
     $newImage = $this->config->item('dataDir') . 'thumbnails/' . $docNameNew . '.jpg';
     $image->generateFromHtml($html, $newImage, $options, true);
     $fileName = str_replace(' ', '-', strtolower($data['fileName']));
     $newPdf = $this->config->item('dataDir') . 'pdf/' . $docNameNew . '.pdf';
     $options = array('viewport-size' => '1250', 'load-error-handling' => 'skip');
     $pdf->generateFromHtml($html, $newPdf, $options, true);
     $config['source_image'] = $newImage;
     $config['maintain_ratio'] = true;
     $config['height'] = 200;
     $this->load->library('image_lib', $config);
     $this->image_lib->resize();
     if (isset($data['department']) && $data['department'] !== '') {
         $department = $data['department'];
     } else {
         $department = $this->session->department;
     }
     $modules = array();
     foreach ($data['modules'] as $module) {
         $modules[] = array('id' => $module);
     }
     $document = array('category' => $data['category'], 'owner' => $this->session->id, 'realname' => $fileName . '.php', 'created' => date('Y-m-d H:i:s'), 'description' => $data['description'], 'status' => 0, 'department' => $department, 'publishable' => 0, 'location' => $docName, 'modules' => json_encode($modules));
     $this->db->insert('documents', $document);
     $fileId = $this->db->insert_id();
     $data = array('fid' => $fileId, 'dept_id' => $department, 'rights' => 1);
     $this->db->insert('dept_perms', $data);
     $data = array('fid' => $fileId, 'uid' => $this->session->id, 'rights' => 4);
     $this->db->insert('user_perms', $data);
     $data = array('id' => $fileId, 'modified_on' => date('Y-m-d H:i:s'), 'modified_by' => $this->session->username, 'note' => 'Initial Import', 'revision' => 'current');
     $this->db->insert('log', $data);
     $msg = array('status' => 'success', 'msg' => 'We successfully created the new document, and inserted the data into the database.');
     echo json_encode($msg);
 }
Ejemplo n.º 20
0
<?php

require_once "vendor/autoload.php";
use Knp\Snappy\Pdf;
if (isset($_POST) && isset($_POST["envoyer"])) {
    $myProjectDirectory = '/var/www/html/mouskipd';
    $snappy = new Pdf();
    $snappy->setBinary('/var/www/html/mouskipd/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64');
    $snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', '/var/www/html/mouskipd/tmp/bill-123.pdf');
    var_dump($snappy);
    echo "<pre>";
    var_dump($snappy);
    echo "</pre>";
}
?>

<form action="index.php" method="POST" accept-charset="utf-8">
    <input type="submit" name="envoyer">
</form>
 /**
  * Prints the service into PDF
  *
  * @param Request  $request
  * @param Response $response
  * @param array    $args
  *
  * @return Response
  */
 public function pdf(Request $request, Response $response, array $args)
 {
     $entity = $this->em->getRepository($this->entityClass)->find($args['id']);
     if ($entity) {
         $ext = pathinfo($request->getRequestUri(), PATHINFO_EXTENSION);
         $isPdf = $ext === 'pdf';
         $content = $this->twig->render($this->views['print'], ['entity' => $entity, 'isPdf' => $isPdf]);
         if ($isPdf) {
             $pdf = new Pdf(getenv('WKHTMLTOPDF'));
             $response->headers->set('Content-Type', 'application/pdf');
             // $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s.pdf"', $entity->getId()));
             $content = $pdf->getOutputFromHtml($content);
         }
         $response->setContent($content);
         return $response;
     }
     throw new NotFoundException();
 }
Ejemplo n.º 22
0
include_once "{$validation}" . "user_validation.php";
include_once $root . '/vendor/autoload.php';
include_once $errors . 'errorProcessing.php';
$pageUrl = urlencode("https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
//validate the user before sending the print operation. This ensures that no
//call to print page can be executed without user session enabled
printValidation($site_prefix, $pageUrl);
use Knp\Snappy\Pdf;
//Pay attention to the path statement to executable -- escape 'spaces with slashes
//Note: When installing the executable make not to install outside of Program Files directory
//The try catch Exception block may not catch anything thrown as the KNLabs-SNAPPY
// classes throw minimal set of Exception
//TODO route exception thrown to site Error page
try {
    $log->debug("printPage.php - set exe location and options");
    $snappy = new Pdf('C://"Program Files/"/wkhtmltopdf/bin/wkhtmltopdf.exe');
    $snappy->setOption('page-size', 'A3');
    $snappy->setOption('disable-external-links', true);
} catch (Exception $e) {
    $log->error("printPage.php - New PDF Class Exception: " . $e->getMessage());
}
if (isset($_POST['url'])) {
    $urlIn = urldecode($_POST['url']);
    $url = setPrintEncryptionUrl($urlIn);
    $log->debug("Use Post to get URL: " . $url);
    header('Content-Type: application/pdf');
    header('Cache-Control: public, must-revalidate, max-age=0');
    // HTTP/1.1
    header('Pragma: public');
    header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
    // Date in the past
Ejemplo n.º 23
0
<?php

require '../autoloader.php';
use OpenBoleto\Banco\Bradesco;
use OpenBoleto\Agente;
use Knp\Snappy\Pdf;
$sacado = new Agente('Fernando Maia', '023.434.234-34', 'ABC 302 Bloco N', '72000-000', 'Brasília', 'DF');
$cedente = new Agente('Empresa de cosméticos LTDA', '02.123.123/0001-11', 'CLS 403 Lj 23', '71000-000', 'Brasília', 'DF');
$boleto = new Bradesco(array('dataVencimento' => new DateTime('2013-01-24'), 'valor' => 23.0, 'sequencial' => 75896452, 'sacado' => $sacado, 'cedente' => $cedente, 'agencia' => 1172, 'carteira' => 6, 'conta' => 0403005, 'contaDv' => 2, 'agenciaDv' => 1, 'descricaoDemonstrativo' => array('Compra de materiais cosméticos', 'Compra de alicate'), 'instrucoes' => array('Após o dia 30/11 cobrar 2% de mora e 1% de juros ao dia.', 'Não receber após o vencimento.')));
$conteudo = $boleto->getOutput();
$lib = getcwd() . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'wkhtmltopdf.exe';
$snappy = new Pdf($lib);
$snappy->generateFromHtml($conteudo, 'nome.pdf');
Ejemplo n.º 24
0
<?php

require_once realpath(dirname(__FILE__) . '/../vendor/autoload.php');
use Knp\Snappy\Pdf;
$parsedUrl = parse_url($_GET['url']);
$url = $_GET['url'];
if ($parsedUrl != false) {
    // add http if needed
    if (!isset($parsedUrl['scheme'])) {
        $url = 'http://' . $_GET['url'];
    }
    $snappy = new Pdf('xvfb-run -s \'-screen 0 1100x1024x16\' -a wkhtmltopdf');
    $snappy->setOption('lowquality', false);
    $snappy->setOption('disable-javascript', true);
    $snappy->setOption('disable-smart-shrinking', false);
    $snappy->setOption('print-media-type', true);
    checkSnappyparams($snappy);
    // Display the resulting pdf in the browser
    // by setting the Content-type header to pdf
    header('Content-Type: application/pdf');
    // Download file instead of viewing it in the browser
    if (isset($_GET['ddl'])) {
        $filename = empty($_GET['ddl']) ? 'file' : $_GET['ddl'];
        header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
    }
    // Convert pdf in CMYK colorspace
    // Need GhostScript
    // Need a writeable temporary directory for php process
    if (filter_input(INPUT_GET, 'cmyk', FILTER_VALIDATE_BOOLEAN)) {
        $tmpRGBFileName = tempnam(sys_get_temp_dir(), 'pdf-rgb');
        $tmpCMYKFileName = tempnam(sys_get_temp_dir(), 'pdf-cmyk');
Ejemplo n.º 25
0
 public function makeFromUri(Request $request)
 {
     // post値の取得
     $data = $request->all();
     $address = $data['address'];
     //$headers = array(
     //"HTTP/1.0",
     //"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
     //"Accept-Encoding:gzip ,deflate",
     //"Accept-Language:ja,en-us;q=0.7,en;q=0.3",
     //"Connection:keep-alive",
     //"User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:26.0) Gecko/20100101 Firefox/26.0"
     //);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $address);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     //curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     $html = curl_exec($ch);
     curl_close($ch);
     // リンクの置換処理
     $url = parse_url($address);
     $protocol = "{$url['scheme']}://";
     $hostName = "{$protocol}{$url['host']}/";
     //var_dump($protocol);
     //var_dump($hostName);
     // リンクの置換(="/),(="//)
     //$html = preg_replace('{="//}', "=\"{$protocol}", $html);
     //$html = preg_replace('{="/}', "=\"{$hostName}", $html);
     // PDFの作成
     $snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
     $snappy->setOption('disable-javascript', true);
     // filename
     $pdfName = date("YmdHis") . ".pdf";
     //$snappy->generateFromHtml($html, storage_path(). "/app/pdf/$pdfName");
     $snappy->generate($address, storage_path() . "/app/pdf/{$pdfName}");
     // htmlをpdfに変換
     return response()->json(array("name" => $pdfName));
 }
 /**
  * Generates the pdf with Snappy
  *
  * @param string $content
  * @param string $path
  *
  * @return string
  */
 protected function doPdf($content, $path, $io)
 {
     $snappy = new Pdf();
     //@TODO: catch exception if binary path doesn't exist!
     $snappy->setBinary($this->wkhtmltopdfPath);
     $snappy->setOption('orientation', "Landscape");
     $snappy->generateFromHtml($content, "/" . $path . 'dc-cheatsheet.pdf');
     $io->success("cheatsheet generated at /" . $path . "/dc-cheatsheet.pdf");
     // command execution ends here
 }
Ejemplo n.º 27
-1
 public function newPDF()
 {
     $snappy = new Pdf();
     $snappy->setBinary('/usr/local/bin/wkhtmltopdf');
     $competences = $app['dao.competence']->findAll();
     return $app['twig']->render('competence.html.twig', array('competences' => $competences));
 }
Ejemplo n.º 28
-1
 /**
  * {@inheritDoc}
  */
 public function generate($path, $html)
 {
     $ext = pathinfo($path, PATHINFO_EXTENSION);
     if (null === $ext) {
         $path .= ".ext";
     } elseif ("pdf" !== $ext) {
         throw new InvalidArgumentException(sprintf("Your destination path must have a .pdf extension for conversion, '%s' passed.", $ext));
     }
     $pdf = new Pdf();
     $pdf->setBinary($this->_getBinDir() . 'wkhtmltopdf-' . $this->_getBinaryType());
     foreach ($this->_options as $key => $value) {
         $pdf->setOption($key, $value);
     }
     if (is_file($path)) {
         unlink($path);
     }
     // Strip out `@font-face{ ... }` style tags as these break the pdf
     $html = preg_replace('/@font-face{([^}]*)}/ms', '', $html);
     $pdf->generateFromHTML($html, $path);
     return new File($path);
 }
    <?php 
require_once 'vendor/autoload.php';
use Knp\Snappy\Pdf;
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf', ['viewport-size' => '1280x800', 'margin-top' => 0, 'margin-right' => 0, 'margin-bottom' => 0, 'margin-left' => 0]);
// Cabeçalho para o navegador entender que o conteúdo é um PDF
header('Content-Type: application/pdf');
// Se quiser forçar o download, descomente a linha abaixo e
// modifica o valor do parâmetro filename para o valor desejado
//header('Content-Disposition: attachment; filename="schoolofnet-blog-home.pdf"');
echo $snappy->getOutput('http://www.schoolofnet.com/blog/');
// Se quiser salvar numa pasta do servidor ao invés mostrar no navegador,
// comente a linha do getOutput(),
// descomente a linha abaixo e arrume o segundo parâmetro.
//$snappy->generate('http://www.schoolofnet.com/blog/', '/app/arquivos/son/home-blog.pdf');