TCPDF: Opening Resulting PDF in Separate Tab or Window

Hi Experts,

I am using TCPDF with PHP in order to generate a report in PDF. After the generation, On my end the PDF open in a separate window in Adobe Reader, however on my client's computers it open on the same tab, then when they click back of course they get "page expired".

Is there any way I can force this to open either in another browser window or browser tab?

Thank you
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Of course!  The PDF document can be written to disk on the server.  The client can see a URL that points an anchor tag to the PDF file on the server disk.  When the client clicks the tag, the new browser window (as shown by the target="xxx" attribute) will open.

If you have any questions or need help with it, please post a link to the "create PDF" script and I'll show you a way to move forward.
0
APD TorontoSoftware DeveloperAuthor Commented:
Here is my code.  I think I need to add something in my final 2 lines...

        //Get Location List & Count
        $sort_by = ($sort_by == 'N' ? 'name' : 'default_time');
        
        $locs = self::get_location_list($archived, FALSE, 1, FALSE, $sort_by, TRUE);
        $loc_count = self::get_loc_count_for_pdf($archived, FALSE);
        
        if ($archived == TRUE){
            $sub_title ='Archived List';
        } else {
            $sub_title ='Active List';
        }        
        
        //Connect to TCPDF
            //Temporarily Change directory to TCPDF to load files...
            $currentDIR = getcwd();
            chdir("../../tcpdf/examples");
            require_once('tcpdf_include.php');

            //Change DIR back
            chdir($currentDIR);
            
            //Setup PDF File
            $pdf = new TCPDF('P', 'mm', array(215.9, 279.4));
            $pdf->SetTitle($sub_title . ' of Locations');
            $pdf->SetMargins(5, 5);
            $pdf->SetAutoPageBreak(TRUE);
            $pdf->setPrintHeader(FALSE);
            $pdf->SetFont('Helvetica', '', 8);
            $pdf->AddPage();
            

        //Setup Title on p.1
            $html = '<table cellpadding="5px" width="100%">';
            
            $html .= '<tr> <td><font size="+5"><b> Location Listing </font><br>'                         
                       .  $sub_title . '</b></td> </tr> </table><br><br>';
            
            $pdf->writeHTML($html);
                
        //Data Container
                                      
            $page_current = 0;
            $page_next = 1;
            $locs_processed = 0;
            
            foreach ($locs as $loc){
                
                //Insert column headers @ top of pafe
                if ($page_current != $page_next){
                                        
                    $html = '<table cellpadding="5px" width="100%">';

                    $html .='<tr> '
                               . '<td align="center" width="25%"> <b> Location </b></td>'
                               . '<td align="center" width="10%"> <b> Code </b></td>'
                               . '<td align="center" width="15%"> <b> Phone </b></td>'
                               . '<td align="center" width="10%"> <b> Default P/U <br>Time </b></td>'
                               . '<td align="center" width="10%"> <b> Default P/U <br>Veh </b></td>'
                               . '<td align="center" width="30%"> <b> Address </b></td>'
                          . '</tr>';
                    
                    $page_current++;
                    $alt = 1;
                    $count = 0;
                    
                    $locs_remaining = $loc_count - $locs_processed;
                    
                    //Define rows per page
                    $max_rows = ($page_current == 1 ? 31 : 34);
                    $max_rows = ($max_rows >= $locs_remaining ? $locs_remaining : $max_rows);
                
                                
                }
                                                
                if($alt == 1){
                    $bg = '#FFFFFF';
                } else {
                    $bg = '#C0C0C0';
                }
                $count++;
                $locs_processed++;
                
                $time = substr($loc['default_time'], 0, 5);
                
                $html .= '<tr>
                                <td bgcolor="' . $bg .'">' . $loc['name'] . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['code'] . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['phone'] . '</td>
                                <td bgcolor="' . $bg .'">' . $time . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['default_vehicle'] . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['address'] . '</td>';
                $html .= '</tr>';
                
                $alt = $alt*(-1);                                                
                                
                if ($count == $max_rows){
                    $html .= '</table>';
                    $pdf->writeHTML($html);
                    
                    //Position Footer at 7 mm from bottom
                    $pdf->SetY(-9);
                    $pdf->SetX(10);

                    $today = new DateTime('today');
                    $today_f = $today->format('F d, Y');
                    $pdf->Cell(0, 0, $today_f, 0, 0, 'left');

                    $page = 'Page ' . $pdf->getAliasNumPage() . ' of ' . $pdf->getAliasNbPages();
                    $pdf->setX(-30);
                    $pdf->Cell(0, 0, $page, 0, 0, 'right');
                    
                    $page_next++;
                    
                    if ($locs_processed != $loc_count) $pdf->AddPage();
                }
            
            $alt++;
                
            }
            
        //Generate File
            $file = 'LocationList.pdf';
            $pdf->Output($file);
        

Open in new window

0
Ray PaseurCommented:
http://iconoun.com/demo/temp_apd_toronto.php
We seem to be missing parts of the application.  When I run it I get this:

Notice: Undefined variable: sort_by in /home/iconoun/public_html/demo/temp_apd_toronto.php on line 9

Fatal error: Cannot access self:: when no class scope is active in /home/iconoun/public_html/demo/temp_apd_toronto.php on line 11

I basically just copied and pasted the script.  Can you please furnish the missing parts, or a mockup of them?  Thanks.

<?php // demo/temp_apd_toronto.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28649357.html
 */
error_reporting(E_ALL);

        //Get Location List & Count
        $sort_by = ($sort_by == 'N' ? 'name' : 'default_time');

        $locs = self::get_location_list($archived, FALSE, 1, FALSE, $sort_by, TRUE);
        $loc_count = self::get_loc_count_for_pdf($archived, FALSE);

        if ($archived == TRUE){
            $sub_title ='Archived List';
        } else {
            $sub_title ='Active List';
        }

        //Connect to TCPDF
            //Temporarily Change directory to TCPDF to load files...
            $currentDIR = getcwd();
            chdir("../../tcpdf/examples");
            require_once('tcpdf_include.php');

            //Change DIR back
            chdir($currentDIR);

            //Setup PDF File
            $pdf = new TCPDF('P', 'mm', array(215.9, 279.4));
            $pdf->SetTitle($sub_title . ' of Locations');
            $pdf->SetMargins(5, 5);
            $pdf->SetAutoPageBreak(TRUE);
            $pdf->setPrintHeader(FALSE);
            $pdf->SetFont('Helvetica', '', 8);
            $pdf->AddPage();


        //Setup Title on p.1
            $html = '<table cellpadding="5px" width="100%">';

            $html .= '<tr> <td><font size="+5"><b> Location Listing </font><br>'
                       .  $sub_title . '</b></td> </tr> </table><br><br>';

            $pdf->writeHTML($html);

        //Data Container

            $page_current = 0;
            $page_next = 1;
            $locs_processed = 0;

            foreach ($locs as $loc){

                //Insert column headers @ top of pafe
                if ($page_current != $page_next){

                    $html = '<table cellpadding="5px" width="100%">';

                    $html .='<tr> '
                               . '<td align="center" width="25%"> <b> Location </b></td>'
                               . '<td align="center" width="10%"> <b> Code </b></td>'
                               . '<td align="center" width="15%"> <b> Phone </b></td>'
                               . '<td align="center" width="10%"> <b> Default P/U <br>Time </b></td>'
                               . '<td align="center" width="10%"> <b> Default P/U <br>Veh </b></td>'
                               . '<td align="center" width="30%"> <b> Address </b></td>'
                          . '</tr>';

                    $page_current++;
                    $alt = 1;
                    $count = 0;

                    $locs_remaining = $loc_count - $locs_processed;

                    //Define rows per page
                    $max_rows = ($page_current == 1 ? 31 : 34);
                    $max_rows = ($max_rows >= $locs_remaining ? $locs_remaining : $max_rows);


                }

                if($alt == 1){
                    $bg = '#FFFFFF';
                } else {
                    $bg = '#C0C0C0';
                }
                $count++;
                $locs_processed++;

                $time = substr($loc['default_time'], 0, 5);

                $html .= '<tr>
                                <td bgcolor="' . $bg .'">' . $loc['name'] . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['code'] . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['phone'] . '</td>
                                <td bgcolor="' . $bg .'">' . $time . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['default_vehicle'] . '</td>
                                <td bgcolor="' . $bg .'">' . $loc['address'] . '</td>';
                $html .= '</tr>';

                $alt = $alt*(-1);

                if ($count == $max_rows){
                    $html .= '</table>';
                    $pdf->writeHTML($html);

                    //Position Footer at 7 mm from bottom
                    $pdf->SetY(-9);
                    $pdf->SetX(10);

                    $today = new DateTime('today');
                    $today_f = $today->format('F d, Y');
                    $pdf->Cell(0, 0, $today_f, 0, 0, 'left');

                    $page = 'Page ' . $pdf->getAliasNumPage() . ' of ' . $pdf->getAliasNbPages();
                    $pdf->setX(-30);
                    $pdf->Cell(0, 0, $page, 0, 0, 'right');

                    $page_next++;

                    if ($locs_processed != $loc_count) $pdf->AddPage();
                }

            $alt++;

            }

        //Generate File
            $file = 'LocationList.pdf';
            $pdf->Output($file);

Open in new window

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Ray PaseurCommented:
Here's my standard "teaching sample" showing many of the basic moving parts.  It produces a clickable link that opens in another browser window.
http://iconoun.com/demo/tcpdf_example.php

<?php // demo/tcpdf_example.php

/**
 * Demonstrate how to put an image into a TCPDF document
 * and write some text over part of the image
 *
 * See http://www.tcpdf.org/doc/code/annotated.html
 */
error_reporting(E_ALL);

// A DATE SETTING MAY BE REQUIRED - DEPENDS ON PHP INSTALLATION SETTINGS
date_default_timezone_set('America/Chicago');

// SYNTHESIZE THE PDF FILE URL AND FILE NAME
$pdf_file_link    = 'storage/tcpdf_example.pdf';
$pdf_file_name    = getcwd() . DIRECTORY_SEPARATOR . $pdf_file_link;

// LOAD THE TCPDF CLASS AND CONFIGURATION
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');

// EXTEND THE TCPDF OBJECT SO WE CAN SUBSTITUTE OUR OWN METHODS
class PDF extends TCPDF
{
    // NULLIFY AUTOMATIC HEADER AND FOOTER
    public function Header() {}
    public function Footer() {}
}

// INSTANTIATE THE OBJECT
$pdf = new PDF('P', 'mm', 'LETTER', true, 'UTF-8', false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(0,0,0,TRUE);
$pdf->SetAutoPageBreak(FALSE);
$pdf->setLanguageArray($l);
$pdf->SetFont('times', '', 13);
$pdf->setCellPaddings(0,0,0,0);
$pdf->setCellMargins(0,0,0,0);

// DO NOT DO THIS
// $pdf->setFillColor(255,255,224);


// APPLY CELL BORDERS, IF NEEDED
$bdr = '1TRBL';

// BUT IF NO CELL BORDER IS NEEDED
$bdr = 0;

// ADD A PAGE
$pdf->AddPage('P', 'LETTER', TRUE);

// ADD AN IMAGE
$img = 'images/ray_padded.png';

// I HAVE NO IDEA WHAT THIS IS DOING TO IMAGE SCALE - EXPERIMENT WITH IT
$pdf->setImageScale(1.53);

// GET THE IMAGE SETTINGS
$pdf->Image
( $img
, 0             // $x
, 0             // $y
, 0             // WIDTH
, 0             // HEIGHT
, 'PNG'         // TYPE
, '#'           // LINK URL
, 'T'           // SET POINTER TOP LEFT
, FALSE         // NO RESIZING
, 300           // DPI
, 'L'           // PALIGN
, FALSE         // ISMASK
, FALSE         // IMGMASK
, 0             // BORDER
, FALSE         // FIT TO BOX
, FALSE         // HIDDEN
, FALSE         // FIT ON PAGE
)
;

// ADD SOME TEXT ON TOP OF THE IMAGE
$pdf->Text
( 24            // $x,
, 24            // $y,
, 'This is Ray'
, FALSE         // $fstroke           = false,
, FALSE         // $fclip             = false,
, TRUE          // $ffill             = true,
, $bdr          // $border            = whatever,
, 2             // $ln                = 0, 2=PUT CURSOR BELOW
, ''            // $align             = '', DEFAULT LEFT
, FALSE         // $fill              = false, CELL BACKGROUND
, ''            // $link              = '', NOT A LINK
, 0             // $stretch           = 0, NO TEXT STRETCH
, FALSE         // $ignore_min_height = false,
, 'A'           // $calign            = 'T', A=FONT TOP INSIDE CELL
, 'T'           // $valign            = 'M', T=VERTICAL ALIGN INSIDE CELL
, TRUE          // $rtloff            = false TRUE = USE PAGE TOP LEFT CORNER TO ALIGN
)
;

// WRITE THE PDF FILE TO THE SERVER
$pdf->Output($pdf_file_name, 'F');

// PRESENT A CLICKABLE LINK SO WE CAN D/L AND PRINT THE PDF
echo '<a target="my_PDF" href="' . $pdf_file_link . '"><strong>Print the PDF</strong></a>';

Open in new window

0
APD TorontoSoftware DeveloperAuthor Commented:
Hi Ray,

I did give this some thought, and I am calling my above script via a submit form, so I can just add a target to it, like in your example.

However, in your example you have a target of "my_pdf", but I thought valid values were "_blank" ?

Thank you
0
Ray PaseurCommented:
The target attribute can use any name (within reason) and the value _blank has the special meaning to open a new anonymous window.  Five clicks on links with _blank would open five new windows.
http://www.w3schools.com/tags/att_a_target.asp
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.