skip to Main Content

DISCLAIMER for duplicate markers: this question is NOT about downloading a file. Please read the question before marking it as a duplicate.

I’m using embed to render a PDF file inside an HTML document. If I proceed as follows:

const embed = document.createElement("EMBED");

const url = "../pdf_files/test.pdf";
embed.src = url;

const content = document.getElementById("content");
content.innerHTML = "";
content.appendChild(embed);

the browser pdf viewer renders the document using the filename, as highlighted in the image below:

enter image description here

But if I use Blob/File/URL.createObjectURL, the pdf viewer does not use the file name:

const embed = document.createElement("EMBED");
const url = "../pdf_files/test.pdf";

const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());

const blob = new Blob([existingPdfBytes], {
    type: 'application/pdf'
});
const file = new File([blob], "hello.pdf", {"type": "application/pdf"});

embed.src = window.URL.createObjectURL(file)

const content = document.getElementById("content");
content.innerHTML = "";
content.appendChild(embed);

enter image description here

Is there a way to set this file name in order to display it properly on the pdf viewer using URL.createObjectURL?

2

Answers


  1. As Kevin Brown pointed out already, essentially the same thing is happening in both scenarios: The last part of the url is displayed at the top.

    embed.src = window.URL.createObjectURL(file)
    console.log(embed.src) // This will show you the url which ends with a uid
    

    Maybe you want to try and set the title of the <embed> to the file name manually:

    embed.setAttribute("title", url.split("/").pop())
    
    Login or Signup to reply.
  2. There is only one common way to tag an objects carrier and that is to specify the Tab Title.

    So you are using HTML and if you also add HTML <title> My name </title> in the files it should title the tab. For icon consider a linked favicon too.

    A fuller description was given as a previous answer.

    If the embed is in a HTML carrier, as it looks like it is here, then simply ensure the <head>er area includes

    <head>
    ...
    <title>MyPDF compliments of Your name goes here</title>
    ...
    </head>
    

    and the body either your embedment or

    <iframe title="My book for you" src="data...etc download="filename as required.pdf" >Description for users</iframe>
    

    Also if possible ensure the PDF has an enbedded /Title=

    https://stackoverflow.com/a/75886544/10802527

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search