You can do this using an <iframe>
element within a custom formatter for a file field.
Field formatters control the output of a field: it's what lets you choose whether to display a generic link, the file name, etc. What you can do is create one that displays the PDF within an <iframe>
element.
To do this, you need to (at a minimum) implement two hooks: hook_field_formatter_info()
and hook_field_formatter_view()
:
/**
* Implements hook_field_formatter_info().
*/
function sandbox_field_formatter_info() {
$info = array();
$info['sandbox_formatter'] = array(
'label' => t('Inline file'),
'description' => t('Display the file within an iframe.'),
'field types' => array('file'),
);
return $info;
}
/**
* Implements hook_field_formatter_view().
*/
function sandbox_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
// Create the proper markup for each item within the field instance
foreach ($items as $delta => $item) {
$path = file_create_url($item['uri']);
$element[$delta] = array(
'#markup' => '<iframe src="' . $path . '"></iframe>',
);
}
return $element;
}
Then you can create a file field, set it to only allow PDF, and choose Inline file as the display format. When you view a node with a PDF, you'll see the PDF within an <iframe>
element.
The above is a very basic, minimal example: for an intermediate example that shows how to implement formatter settings, check out Dan Linn's tutorial. Also be sure to check out the relevant API pages, which includes sample implementations even more advanced than Linn's:
As an aside, it should be noted that there are a couple of related modules:
- Iframe: creates an
<iframe>
element formatter, but it hasn't been ported to Drupal 7 yet.
- Custom formatters: claims to allow the creation of custom formatters without needing to create a custom module