Guide on loading a PDF asset dynamically within an Angular application with the help of webpack

I am having trouble loading a PDF file into my Angular app, which is running on the webpack dev server. I am using the HTML <object> tag with the data attribute to achieve this.

The issue arises because the PDF path is generated dynamically at runtime and it's an absolute path like C:\test.pdf.

Instead of displaying the PDF in the UI, the console displays the error message -

Not allowed to load local resource: file:///C:/test.jpeg

Interestingly, the production build of the app, which runs as static HTML rather than on a hosting server, works fine. Relative paths also work without any issues.

How can I successfully load the PDF file?

webpack.common.js

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

const path = require('path');
const rootDir = path.resolve(__dirname, '..');

module.exports = {
resolve: {
    extensions: ['.js', '.ts'],
    modules: [rootDir, path.join(rootDir, "node_modules")]
},

module: {
    rules: [
        {
            test: /\.html$/,
            loader: 'html-loader'
        },
        {
            test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
            loader: 'file-loader?name=assets/[name].[ext]'
        },
        {
           test: /\.(scss|css)$/,
           use: [
                { loader: "style-loader" },
                { loader: "css-loader" },
                { loader: "sass-loader",
                    options: {
                        includePaths: ["node_modules/"]
                    }
                }
            ]
        }
    ]},
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }),
        new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core(\\|\/)@angular/,
            path.resolve(__dirname, '../src')
        )
    ]
};

webpack.dev.js

var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');

const path = require('path');
const rootDir = path.resolve(__dirname, '..');

commonConfig.entry = {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
};

commonConfig.module.rules.unshift({
    test: /\.ts$/,
    loaders: ['awesome-typescript-loader', 'angular2-template-loader', 'angular-router-loader']
});

module.exports = webpackMerge(commonConfig, {

  devtool: 'cheap-module-eval-source-map',

  output: {
      path: path.resolve(rootDir, 'dist'),
      publicPath: 'http://localhost:8080/',
      filename: '[name].js',
          chunkFilename: '[name].chunk.js'
      },

      plugins: [
          new ExtractTextPlugin('[name].css')
      ],

      devServer: {
          historyApiFallback: true,
          stats: 'minimal'
      }
});

Answer №1

To specify the location from where the devServer serves files, you can configure it like this:

devServer: {
  historyApiFallback: true,
  stats: 'minimal',
  contentBase: ['./dist', 'C:\\']
}

After setting up the devServer, you can load your file using

<... src="/file_name.ext" ... />

However, I advise against adding C:\ as the contentBase. If possible, designate a different directory for storing your generated PDF files.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What strategies can be employed to maintain reliable datetime management for a reservation system operating in diverse time zones?

Looking at the big picture: An interesting scenario arises when a hotel owner specifies a time frame for booking reservations at a restaurant (5pm - 10pm). Along with this information, there is also a timezone provided to ensure that dates are displayed i ...

What strategies can I implement to ensure my modal dialog box remains responsive? Adjusting the window size causes the modal box to malfunction and lose its structure

Whenever I adjust the size of the browser window, the elements inside the modal box become misaligned. HTML <div class='modal'> <div class='modal-content'> </div> </div> Below is the CSS for the modal ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

Is there a way to upload multiple files using expressjs?

I'm looking for a way to efficiently send multiple files, including an entire directory, so that I can access them in another JavaScript file called from an HTML file. const app = require("express")(); const http = require("http"). ...

Executing javascript href using Python in Selenium

Currently, I am attempting to use Selenium in Python to click on a href JavaScript link. The HTML code appears as follows: HTML Example and my goal is to click on javascript:goType(1). This is the approach I have taken: advance_search = browser.find_el ...

What is the proper way to utilize a function in C# that integrates with a window form using TypeScript?

I am currently working on a code that is in c# and utilizes a web browser. My goal is to convert the existing JavaScript code to Angular 7 and Typescript. Below is the c# code and the corresponding JavaScript code used to access the c# function from JavaS ...

What is the process for converting a string into a date while disregarding the time zone

Due to the way dates are stored, it is important for me to retrieve them exactly as they are stored, but time zones are causing issues. moment("2020-10-28T08:41:00.000Z").format("YYYY-MM-DD HH:mm") // Result: 2020-10-28 09:41 However, ...

What is the best way to finish up the JavaScript code below?

Having just started learning JavaScript, I am struggling to figure out how to use JavaScript to clear the text in a text box and move it below the box when a user starts typing. I've been watching this tutorial http://codepen.io/ehermanson/pen/KwKWEv ...

The node.js application was unable to locate the '../HMS/server/models/user' file

Hi there! I'm currently working on an application with a folder structure as shown below. I want to use the following line in my passport.js file: var User = require('../server/models/user'); However, I encountered the error below after tr ...

Panel floating with Bootstrap framework

I have created a unique two-column layout using Bootstrap, utilizing the col-md-6 class. The layout consists of a row with a panel at the top containing a table, a left column panel displaying a list of media items, and a right column panel containing text ...

Deleting a folder using npm prior to the build process

Can someone help me with this issue? I have the following script: "build": "rimraf dist webpack --progress --config webpack/prod.js", However, instead of just removing the 'dist' folder, it is removing all files inside the 'webpack' fol ...

Issue with slideout menu hyperlinks malfunctioning

Currently developing a site at , everything seemed ready for deployment until testing in 320x480 mode on mobile revealed that the links on the slideout menu were not working on any mobile device I tried, regardless of resolution or page. I've tried u ...

Steps to avoid the button being submitted twice

I am facing an issue with two buttons in my code. One button is used to increase a count and the other button is meant to submit the count and move to the next page. The problem is that when I click on the "Proceed" button, it requires two clicks to procee ...

The res.send() function is being executed prior to the async function being called in express.js

My current project involves creating an API that returns epoch time. I am using an express.js server for this, but the issue arises when the res.send() function is called before the getTimeStamp() function finishes executing. I tried looking up a solution ...

Activate the Jquery-ui Tooltip with a click event

Here is the code I'm using: function DrawTipsProgress(postid, ajaxurl) { var data = { action: 'ajax_action', post_id: postid } jQuery('#dashicon-' + postid).on("click", function () { jQuery.p ...

Dynamic content for tooltips in Angular

Currently, I am facing a challenge where I need to dynamically populate content in a tooltip by executing a function with a parameter. This parameter holds the crucial information required to update the tooltip content. The complexity arises from the fact ...

Issue with Angular 6: Textarea displaying value as Object Object

I have data saved in local storage using JSON.stringify, and I want to display it in a textarea. Here are the relevant code snippets: { "name": "some name" } To retrieve the data, I'm using this: this.mydata = localStorage.getItem('mydata&a ...

When I try to post using the raw feature in Postman in Node.js, the post ends up empty

My API is supposed to receive data for saving in the database. However, when I call the PUT method, my req.body.nome returns empty. It works fine with form-urlencoded, but I've tried using body-parser and it's deprecated. Here is my request usin ...

Extracting JavaScript OnClick button using Selenium

I'm having trouble extracting the email address from the following URL: https://www.iolproperty.co.za/view-property.jsp?PID=2000026825 that is only visible after clicking on the "Show email address" button. However, every time I attempt to click and r ...

Error encountered in node.js script due to misuse of Sqlite's SQLITE_MISUSE functionality

Upon running my code with this query, I have encountered a situation where all tables are listed sometimes, while other times only one table is shown and consistently the following error is displayed: Query Error: Error: SQLITE_MISUSE: unknown error I ha ...