Home > Back-end >  Dompdf creates new output pdf-document, I need to output content in one file, how to fix it?
Dompdf creates new output pdf-document, I need to output content in one file, how to fix it?

Time:02-24

I'm new with this library. I installed it without composer, do all by instructions. Yes, it's wordpress, but I need to do my task exactly manually, not with plugins, and I want to learn that library, it seems to be a good thing. That's how I install dompdf.

require get_template_directory() . '/pdf-test.php';
require_once get_template_directory() . '/assets/dompdf/autoload.inc.php';
 use Dompdf\Dompdf;
 $dompdf = new Dompdf();
 ob_start();
require(get_template_directory().'/pdf-test.php');
 $content_pdf = ob_get_clean();
 $dompdf->loadHtml( $content_pdf);
 // (Optional) Setup the paper size and orientation
 $dompdf->setPaper('A4', 'landscape');
 // Render the HTML as PDF
 $dompdf->render();
 // Output the generated PDF to Browser 
$output= $dompdf->output();
 $dompdf->stream();

Pdf-test.php has to be the output file. Now it's simple, nothing special

<?php  
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

?>
<div  style="font-family: Dejavu Sans, sans-serif;">
    hello
</div>

<?php 

What at all I plan to do? To attach pdf-test.pdf to user emails. There will be dynamic content, special, so that's why plugins wouldn't help me.

add_filter( 'woocommerce_email_attachments', 'attach_terms_conditions_pdf_to_email', 10, 3);

function attach_terms_conditions_pdf_to_email ( $attachments , $id, $object ) {
    $your_pdf_path = get_template_directory() . '/pdf-test.pdf';
    $attachments[] = $your_pdf_path;
    return $attachments;
}

In emails users have to open that attached pdf-file in browser. With random pdf from the Internet it works great, so the idea is not dead, now I want to create my own.

When I load or reload the page, the new pdf-file is creating and downloading as document.pdf, and if I save it I successfully open it in the browser, I see my 'hello'.

But that's not what I need - I need to generate the content not to new document.pdf file, I need to generate it into pdf-test.pdf, that I will attach where I need. It has to be with dynamic content, but one for all. How to change the output way and to open not empty pdf-test.pdf in browser?

CodePudding user response:

$dompdf->stream(); outputs to browser so if you don't want that happening remove that line.

$dompdf->output(); creates the PDF as a string so you could save it as a file:

$output = $dompdf->output();
file_put_contents(get_template_directory() . '/pdf-test.pdf', $output);
  • Related