Open main menu

Extension talk:EmbedPDF


Degrading Gracefully - Mac OS X and inline PDFsEdit

Hi, this extension works pretty well, it's nice and simple, and does the job as expected. I have however made a small change to the code to help it degrade gracefully, for example:

Where I work currently has a mixed environment of Mac OS X and Windows. Firefox on OS X does not display inline PDFs, basically adobe haven't made a plugin, so it will show a 'this page has missing plugins' and searching will fail because there is no official one.

Sam Gross has made a Intel-only firefox addon quicklook plugin that allows firefox to view them actually in browser, so that scratches my itch.

but as it is currently, if any inline-pdf viewer is not found, it simply displays white space, which tells the user nothing if they were not expecting a pdf to be displayed inline on page and even if they were it does not help them in the slightest and provides no solution.

The same would go for a windows computer with adobe not installed.

I've modified the HTML output, just on line 26, i sourced this solution here.

function makeHTMLforPDF ($path) {
  return '<object data="'.$path.'" width="700" height="600" type="application/pdf">
You are unable to view this PDF within the webpage as there is no plugin available for your browser. You can still <a href="'.$path.'">download the PDF file here</a> for viewing locally.

That at least gives the user a bit more info. What does the developer think? I think that this(or something similar) should be integrated. feel free to use that. :)

To provide a more complete solution for users here I wrote a quick and dirty php file hosted elsewhere that serves my needs locally, that does some quick checks to see if they're using firefox, if they're on an intel or ppc mac (we only have 1), or if they're running something else.

if they're on an intel mac it'll redirect them to the plugin, ppc it'll tell them they're out of luck and anything else it'll tell them to install adobe reader.

But, for most MediaWiki projects, I wouldn't think it's appropriate to be directing to third party plugins for support or anything els, so telling them what the problem is and an alternative is enough :).

here's the quick and dirty php hack redirect if anybody finds it useful. it's literally the first code I've posted to the Internet, it works for me, sanity check it for your needs.

//I've created this because adobe have no way to embed pdfs inline within firefox. gah.
//Read more about why this php file was created:
//Checking whether firefox is used
if(strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== FALSE)
if(strpos($_SERVER['HTTP_USER_AGENT'], 'Intel Mac OS X') !== FALSE)
// Permanent redirection
header("HTTP/1.1 301 Moved Permanently");

if(strpos($_SERVER['HTTP_USER_AGENT'], 'PPC Mac OS X') !== FALSE)
{ echo "Unfortunately, due to you being on an older (PPC) mac, you cannot view PDF's inline on the wiki.<p> To view PDFs, you will need to download them to your local computer.";

else{echo "Adobe Reader may need to be installed/reinstalled on your system, it has not been detected.  <A HREF=\"\">Click here for the latest release</A>";


If anyone else than me finds this useful, dropping me a note on my userpage would be nice :).


update: i just had a look at some of the other issues on this page, you'll see that others are having the issue, and had no idea of the fix.

mine is similar to the solution down the bottom, except mine has some explanatory text, and a link to the file.

The icon for a pdf is interesting, but not supported by default in mediawiki, there's no pdf icon, but my text and link works.

Docs from localhostEdit

Hy there! I don't really have experience with this kind of extensions and I was wondering if you could help me. I am using your code and unfortunatelly it does not work when I want to embed docs which are on the local host. Do u have any idea why :(


Sorry--I just can't get you exactly...

What is the wiki code you're using? Is it something like "<pdf>http://localhost/my/path/to.pdf</pdf>"? Does any error occur? Is your Web server okay with PDFs (what does it show if you open "http://localhost/my/path/to.pdf" in a Web browser)?

--Dmitry Shurupov 16:20, 21 February 2009 (UTC)

As written, the regex insists upon a period character (‘.’) in the domain name (like ‘’). Fix this by inserting a question mark after the period character: in EmbedPDF.php, change

if (preg_match('/^http\:\/\/[\w\-_]+(\. (etc.)


if (preg_match('/^http\:\/\/[\w\-_]+(\.? (etc.)

Scorwin 15:31, 10 November 2009 (UTC)

URI error (semantic forms extension)Edit

Thanx for this extension, it works great here. However I got one issue that maybe easily can be solved. I like to use this extension together with the semantic form extension. In a form the user can upload a pdf-file which will be printed on the outputpage. I like to embed the pdf and not only the filename. I got it working with images but can't get it to work with EmbedPDF. The variable is called {{{inputfilename}}} so <pdf>{{{inputfilename}}}</pdf>should have to do the trick. But I got the 'Error: bad URI in <pdf>!' message after saving the page. I guess it means it doesn't recognize the '{'. Is there a way I can make an exception in the extension that it does read the whole text between <pdf> and </pdf> as a filename?

-Jos, 19-2-2009


Allowing "{{{inputfilename}}}" in <pdf> is rather simple--you just have to add few lines into the "embedPDFHandler" function. It will look like this:

function embedPDFHandler ($input) {
  if (!$input) return '<font color="red">Error: empty param in &lt;pdf&gt;!</font>';

  if (preg_match('/^\{\{\{[^\}]+\}\}\}$/', $input))
    return makeHTMLforPDF($input);

  if (preg_match('/^[^\/]+\.pdf$/', $input)) { 

However, it will make a trick if the "{{{file}}}" string will be transformed to the URI by semantic forms extension. I don't know how it works--so, I'm not sure if it is okay.

If the problem still exists, please, let me know--I'll give the semantic form extension a try...

--Dmitry Shurupov 16:19, 21 February 2009 (UTC)

Still same errorEdit

Thanx for the answer. I added the lines though I still got the same error. I'm not quite an expert in php so forgive me if there might an 'easy' solution to my problem.

I guess I got images working because images in wiki got a special syntax: [[Image:]] instead of the <img>-tag. Perhaps there is a way to hack the code so that something like [[Pdf:{{{file|}}}]] can be made instead of <pdf>...</pdf>?
--Jos, 26 February 2009

Installed, no errors, just not displaying the PDF in FirefoxEdit

I've installed EmbedPDF.php in the extensions directory. I added the requireonce line.

I created a new page, with one line: (I've removed the domain name)

and the page is there, but the pdf isn't embeded in Firefox 3.06. It's Embeded in I.E. 7.x just fine.


Please, read the "Usage" section.

You have to add the lines like this for URLs:


And lines like this for PDFs uploaded to your MediaWiki:



Thanks for this extension. It's only in Internet Explorer (tested on v. 8) I'm having difficulties viewing the embedded pdfs. But I still wanted to use this extension, since there aren't any other ones dealing with this problem. I've added a link to the object, so browsers that won't show the embedded pdf, come up with a link instead. Now Opera, Firefox and Chrome show the embedded pdfs properly, while Internet Explorer shows a link. This is an acceptable solution for me, and maybe this idea would work for others as well?

Add the following around line 25-27 in EmbedPDF.php:

 function makeHTMLforPDF ($path) {
   return '<object data="'.$path.'" width="700" height="600" type="application/pdf"><a href="'.$path.'">
           <img src="" width="20" height="20" border="0">
           </a> <a href="'.$path.'">Download document</a></object>';

It seems that the new feature compability view in Internet Explorer might have something to do with this problem. Any ideas, Dmitry?
-- Marius, July 2009

Worked in mw 1.14.0, broke in mw 1.15.1 ?Edit

I have been using this extension happily on a WAMP installation for an intranet with mediawiki 1.14.0. I have just tried to install it on a linux server running mediawiki 1.15.1, and mw complains about the header already being created. I suspect there is a simple fix, but I don't know it. Any help out there? TIA. Mickeyf 2009/11/18

It's working fine for me with 1.15.3, PHP 5.2.13, Firefox 3.6.3, and Adobe Reader 9.3.2 on CentOS. -- 15:47, 22 June 2010 (UTC)
I'm using 1.15.1 and I think, I had the same problem, but I can't really remember how I fixed it. Try leaving out the ending ?> - that's the only difference I found in my version. Sidcom 11:18, 23 June 2010 (UTC)
It was working for me earlier per my comment above, and now it stopped working all of a sudden. -- 16:47, 28 June 2010 (UTC)
Do you get the same error? Sidcom 16:56, 28 June 2010 (UTC)

EmbedPDF does not handle https URIsEdit

EmbedPDF does not handle https URIs. If a wikipage contains code such:


Then it says: Error: bad URI in <pdf>!

Broken imageEdit

After inserting the code:


The rendered wiki page displays a broken image.

  • MediaWiki 1.17alpha
  • InternetExplorer 8.0

Local network file shareEdit

Is it possible to adjust the code to except "file://" addresses or "\\[network share name]\" addresses instead of only "http://"?
My PHP knowledge is quite limited and I was unsuccessful in all my attempts.

New featuresEdit

Hi, i added some extra features to EmbedPDF extension. If you find them useful, please check the attached php file.


  • Image height/width

New Sintax:




  • Interactive Button

When pressed a popup message will show up and asks where to load the pdf file (current page or new one)





 * MediaWiki EmbedPDF extension
 * @version 0.1
 * @author Dmitry Shurupov
 * @link

$wgExtensionCredits['parserhook'][] = array(
  'name' => 'EmbedPDF',
  'author' => 'Dmitry Shurupov',
  'version' => '0.1',
  'url' => '',
  'description' => 'Allows to embed .pdf documents on a wiki page.',

$wgHooks['BeforePageDisplay'][]  = 'MyExtensionJavaScript';

function MyExtensionJavaScript( $out ) {
        $script='<script type="text/javascript">
                function managePdf(filename,filepath) {
                        var omyButton = document.getElementById("myButton");
                        var omyFrame = document.getElementById("myFrame");
                        var buttonValue = omyButton.value;

                        if(buttonValue.indexOf("Open") != -1) {
                                var answer = confirm ("Open for an new window?");
                                if (answer) {
                                else {
                                        omyButton.value = "Close " + filename;
                        else {
                                omyButton.value = "Open " + filename;

                function openPDFWindow(filepath)


                $out->addScript( $script );

                return true;

$wgExtensionFunctions[] = 'registerEmbedPDFHandler';

function registerEmbedPDFHandler () {
  global $wgParser;
  $wgParser->setHook( 'pdf', 'embedPDFHandler' );

function makeHTMLforPDF ($path, $w, $h) {
        $filename = str_replace("\n", "", basename($path).PHP_EOL);
        $filename_quoted = "'".$filename."'";
        $filepath_quoted = "'".$path."'";

                return '<object id="myFrame" style="display:none" data="'.$path.'" width="'.$w.'" height="'.$h.'" type="application/pdf"></object>
                        <input id="myButton" type="button" value="Open '.$filename.'"  onclick = "managePdf('.$filename_quoted.','.$filepath_quoted.')"/>';

function embedPDFHandler ($input, $argv) {
  if (!$input) return '<font color="red">Error: empty param in &lt;pdf&gt;!</font>';

  $input_array = explode('|', htmlspecialchars($input));
  $input = current($input_array);
  $w  = (count($input_array) > 1 && is_numeric($input_array[1])) ? $input_array[1] : 425;
  $h = (count($input_array) > 2 && is_numeric($input_array[2])) ? $input_array[2] : 350;

  if (preg_match('/^[^\/]+\.pdf$/', $input)) {
    $img = Image::newFromName( $input );
    if ($img != NULL) return makeHTMLforPDF($img->getURL(),$w,$h);

  if (preg_match('/^http\:\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@\?\^\=\%\&:\/\~\+\#]*[\w\-\@\?\^\=\%\&\/\~\+\#])?\.pdf$/', $input))
    return makeHTMLforPDF($input,$w,$h);
  else return '<font color="red">Error: bad URI in &lt;pdf&gt;!</font>';


Waow, I do love this new "version" but it doesn't work for me using FireFox or Internet Explorer with MediaWiki 1.16.
I do have the button but nothing append when I click it.
Any way to fix it ? From MoBO 11:54, 17 February 2011 (UTC)

Hi, i use the new version with Mediawiki 1.16 and FireFox.
You must e litle change in function makeHTMLforPDF. (Sorry for my bad englisch)

$filename = str_replace("\n", "", basename($path).PHP_EOL);

$filename = str_replace("\n", "", basename($path));

--Speedy McCat. Keiner ist unnütz, er kann immer noch als schlechtes Beispiel dienen. 13:40, 25 March 2011 (UTC)

Zoom to document width?Edit

Is there a way to show the pdf zoomed to the document width, by default?

Broken in the version 1.18Edit

This is the source of the error:

$img = Image::newFromName( $input );

The class Image is excluded in the version 1.18. Solution:

$img = wfFindFile(Title::makeTitle(NS_IMAGE, $input));

This works fine for me at, Hakeld 22:45, 28 January 2012 (UTC)

Nesting a magic word within EmbedPDF?Edit

I noticed that the "URI error" thread addresses something similar, but the suggested code hasn't worked for me.

In particular, I'd like to be able to have embedpdf automatically work on any File:File.pdf page so that upon visiting File:File.pdf, the pdf file is automatically displayed as embedded.

I thought to try the following function on every page that exists for an uploaded file:


However, even when I adjust the regular expression in a similar way as you suggested by writing,

if (preg_match('/^\{\{[^\}]+\}\}$/i', $input))

return makeHTMLforPDF( $input, $argv );

The magic word {{PAGENAME}} is not resolving so it returns {{PAGENAME}}, rather than File.pdf

Thanks in advance for any help,

The fast hack is to add these two lines:

  global $wgParser;
  $input = $wgParser->replaceVariables($input);

In the beginning of the embedPDFHandler function.

--Dmitry Shurupov 17:22, 15 February 2012 (UTC)

Responsive DesignEdit

I made the following changes to the extension to allow the embedded PDF be responsive to the available width. This is based on Embedded Objects in Responsive Design.

I also provide a download option (based on suggestion above). If the user's browser does not support the object, the user will still see the logo and download link.

function makeHTMLforPDF( $path, $argv ) {
	$embed_html = '<div class="embed-container"><object data="' . $path . '" type="application/pdf"></object></div><br /><a href="'.$path.'">';
	$embed_html .= '<img src="" width="40" height="40" border="0">';
	$embed_html .= '</a><br /><a href="'.$path.'">Download document</a>';
	return $embed_html;	 

Here is the CSS used to style the embedded object.

.embed-container {
    position: relative;
    padding-bottom: 56.25%; /* 16/9 ratio */
    padding-top: 30px; /* IE6 workaround*/
    height: 0;
    overflow: hidden;
.embed-container iframe,
.embed-container object,
.embed-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

--Lotusjeff (talk) 13:29, 16 May 2013 (UTC)


is it possible that the Adobe pageview and toolbar is shown in the document automatically?

It works like that for meEdit

Your browser's default pdf reader is what will be used

1.19 CompatibilityEdit

It doesn't seem to work well with 1.19.1 After adding it, it locks up the browser when entering edit mode...

It functions for me on 1.19.2. --Inops (talk) 09:25, 22 October 2012 (UTC)

Doesn't work?Edit

I did these 3 things:

  1. Created a text file called EmbedPDF.php which contains the required php code.
  2. Copied the file into the MediaWiki extensions folder on the server.
  3. Added to the end of LocalSettings.php: require_once("$IP/extensions/EmbedPDF.php");

Still, the extension and PDF file are not recognized. The wiki page just shows the pdf tags between brackets, and the filepath between them.

Any clues? Thanks

Return to "EmbedPDF" page.