Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a PDF's meta title that appears in the browser tab in PHP?

I have a PDF that has been generated with wkhtmltopdf, but it does not have a title. Therefore, browsers use the last part of the URL for the tab's title and the PDF preview title. I would like to change the title that appears in those places.

I understand that this is defined by the meta title of the PDF document, but how can I go about changing it in PHP?

Example of a PDF with no meta title

like image 280
Émile Perron Avatar asked Dec 07 '25 14:12

Émile Perron


2 Answers

If you open a PDF in your text editor, you will notice that the meta title is defined in the first section, which is delimited by << and >>. It looks like the following:

/Title (My Document Title)

or:

/Title (��)

As you can see, the pattern is quite simple. All you have to do is replace that line using the same pattern, except with your title between the parentheses.

Although this is most likely not the cleanest or the most efficient solution, a simple preg_replace can do the trick just fine for this type of thing.

Here is an example using an existing PDF:

$filename = '/my/path/to/file.pdf';
$content = file_get_contents($filename);
$title = str_replace(['(', ')'], '', $title);
$title = utf8_decode($title); # Deals with accented characters and such
$updatedContent = preg_replace('/\/Title \(.*\)/', '/Title (' . $title . ')', $content);

If the meta title is missing from the file, you can simply insert it where it would've been.

Afterwards, you can do whatever you like with the updated data. You can save it back to the file in order to update the existing PDF:

file_put_contents($filename, updatedContent);

Or, you can display the PDF to your user:

header('Content-type: application/pdf');
header('Content-disposition: inline; filename="my-updated-file.pdf"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
echo $updatedContent;
die();

The possibilities are endless! (well, not really, but you get the idea)

Hope this was helpful!

like image 95
Émile Perron Avatar answered Dec 11 '25 20:12

Émile Perron


wkhtmltopdf has command-line arguments to set various aspects of the document, including the title.

--title

sets the document title


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!