WordPress, View a PDF file in a webpage


  • First of all create a wordpress template by using the following code:


/**
  Template Name: ViewPDF
*/

header('Content-type: application/pdf');

if (have_posts()) : while (have_posts()) : the_post();

        $args = array(
            'post_type' => 'attachment',
            'numberposts' => 1,
            'post_status' => null,
            'post_parent' => $post->ID
        );

        $attachments = get_posts($args);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                $pdfPath=get_attached_file($attachment->ID, $unfiltered);
	        header('Content-Length: '.filesize($pdfPath));
                echo file_get_contents($pdfPath);
            }
        }

    endwhile;
endif;

  • Create a new page and select the new created template for this page.
  • Import the pdf file as the page attachment, save the page.
  • That’s it, now browse the new created page to see the PDF file.
Advertisements

One response to “WordPress, View a PDF file in a webpage

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s