How to open pdf in separate window for custom links in Magento?

How to open pdf in separate window for custom links in Magento?

October 14, 2026 · Illustrated author avatarBy Stefan Bogdanescu
How to open pdf in separate window for custom links in Magento?

As an experienced eCommerce developer specializing in Magento, I often encounter challenges related to handling custom links and opening external files such as PDFs in separate windows or tabs. In this post, I’ll walk you through a step-by-step guide on how to achieve this functionality for your specific requirement.

The Current Challenge

You’ve set up a static page with a list of links, where each link corresponds to its own PDF file. However, when a user clicks these links, the PDF doesn’t open in a new window; instead, it replaces the current page content or opens in the same tab.

To resolve this issue, we’ll need to modify the behavior of these links and ensure they trigger a new browser window for each PDF download.

Step 1: Prepare Your PDF Files

Before proceeding with the code implementation, make sure your PDF files are properly uploaded to Magento. You can do this by placing them in the pub/media directory or using the built-in Media Gallery for better organization and management.

For example, let’s assume you have a file named document1.pdf, which is located at pub/media/documents.

Step 2: Create the HTML Page

In your static page template (e.g., app/design/frontend/Vendor/Theme/templates/page/static.phtml), create an unordered list (<ul>) to display your links:

<ul class="pdf-links">
    <li><a href="{{ view->getUrl('no-route') }}">Link 1</a></li>
    <li><a href="{{ view->getUrl('no-route') }}">Link 2</a></li>
    <!-- Add more links as needed -->
</ul>

Note that we’re using {{ view->getUrl('no-route') }} to generate a dummy URL for each link. Don’t worry; we’ll fix this in the next step.

Step 3: Modify the JavaScript

To open the PDF files in new windows, we need to add some custom JavaScript code that listens for click events on our links and forces them to open in separate tabs or windows.

Create a new file named pdf-links.js inside your theme’s JavaScript folder (e.g., app/design/frontend/Vendor/Theme/js) with the following content:

require(['jquery'], function($) {
    $(document).ready(function() {
        $('.pdf-links a').click(function(event) {
            event.preventDefault();
            var pdfUrl = this.href + '?direct_download=true';
            window.open(pdfUrl, '_blank');
        });
    });
});

This script uses jQuery to bind a click event handler to all a elements inside the .pdf-links container. When a link is clicked:

  1. The default browser behavior (which would cause the current page to reload) is prevented.
  2. A new URL is generated by appending ?direct_download=true to the existing href attribute of the anchor element.
  3. This updated URL is passed to the window.open() function, which opens it in a new window or tab.

Step 4: Enqueue Your JavaScript File

To include this custom JavaScript file on your static page, add the following code to your Magento theme’s layout XML file (usually located at app/design/frontend/Vendor/Theme/layout/default.xml):

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="head">
            <script src="Vendor_Theme::js/pdf-links.js"/>
        </referenceContainer>
    </body>
</page>

Replace Vendor with your actual vendor name.

Step 5: Modify the Controller

Now, we need to update our dummy URL generated by {{ view->getUrl('no-route') }} in the previous steps. Instead of a static route, we’ll create a custom controller action that returns a direct download link for the specified PDF file.

Create a new controller class named PdfController.php inside your Magento module’s controller directory (e.g., app/code/Vendor/Module/Controller/Pdfcontroller.php) with the following content:

<?php

namespace Vendor\Module\Controller;

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Result\PageFactory;

class PdfController extends \Magento\Framework\App\Action\Action
{
    protected $resultJsonFactory;

    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
    }

    public function execute()
    {
        $filePath = 'pub/media/documents/document1.pdf';
        $pdfContent = file_get_contents($filePath);

        if ($pdfContent !== false) {
            $response = $this->resultJsonFactory->create();
            $response->setHttpResponseCode(200);
            $response->setHeader('Pragma', 'public');
            $response->setContent($pdfContent);
            $response->setHeader('Expires', 'Tue, 1 Jan 2000 0:00:00 GMT');
            $response->setHeader('Cache-Control', 'must-revalidate');
            $response->setHeader('Content-Type', 'application/pdf');
            $response->setHeader('Content-Disposition', 'attachment; filename="document1.pdf"');

            return $response;
        } else {
            // Handle case when the file is not found
            // You can add your own error handling or logging here
        }
    }
}

This controller action retrieves the content of the specified PDF file and returns it as a direct download response with appropriate headers.

Finally, we need to update our dummy URLs in the static page template (app/design/frontend/Vendor/Theme/templates/page/static.phtml) by replacing {{ view->getUrl('no-route') }} with the actual route for our custom controller action:

<ul class="pdf-links">
    <li><a href="{{ view->getUrl('vendor_module/pdf/download', ['_secure' => true]) }}">Link 1</a></li>
    <li><a href="{{ view->getUrl('vendor_module/pdf/download', ['_secure' => true]) }}">Link 2</a></li>
    <!-- Add more links as needed -->
</ul>

Replace vendor_module with the name of your actual Magento module.

Conclusion

By following this comprehensive guide, you should now be able to open PDF files in separate windows or tabs when clicking on custom links within a static page in Magento. The solution involves creating a custom JavaScript file, updating the layout XML, and implementing a controller action for direct downloads.

Remember that proper file management and organization are crucial for maintaining an efficient eCommerce environment. Consider using modules like the built-in Media Gallery to streamline your PDF uploads and management processes.

For more advanced Magento development techniques and best practices, feel free to explore our blog on Laravel Company. We regularly publish articles covering various aspects of Magento development and eCommerce solutions.

Themes Orders Errors CLI

Our network