Émile Perron
Émile Perron

Reputation: 883

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

Upvotes: 3

Views: 7908

Answers (3)

Genki
Genki

Reputation: 489

If using PHP's dompdf package to create pdf files, do this:

$dompdf->add_info('Title', 'Your meta title');
$dompdf->render();

source: How to add meta title to a PDF on the browser tab using dompdf?

Upvotes: 0

user10051234
user10051234

Reputation:

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

--title

sets the document title

Upvotes: 2

Émile Perron
Émile Perron

Reputation: 883

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!

Upvotes: 4

Related Questions