skip to Main Content

Trying to Embed PDF into my HTML Web Page for which I am calling an AJAX function.

The function retrieves the data from my backend of the PDF but instead of rendering that as PDF, my frame keep showing the data of that PDF as shown in screenshot.

Any suggestion on how to make my page render it into PDF, as webpages by default support showing PDFs.

My data from backend is in byte[] format, further suggestion to improve

2

Answers


  1. Chosen as BEST ANSWER

    So I had asked this question. And, after some research, I found out that the approach was right, but I was omitting crucial headers which indicated that the data being sent from the backend is to be rendered as PDF or image.

    So if any one working on spring boot and facing same problem can follow this:

    1. Controller – endpoints mapping:

      1

      @GetMapping(
          path = "/documentExplore/{documentId}",
          produces ={
              MediaType.APPLICATION_PDF_VALUE,
              MediaType.IMAGE_PNG_VALUE
          }
      )
      public byte[] viewDocument (@PathVariable(value = "documentId") Long documentId)
      throws IOException, InterruptedException, SQLException, DocumentException
      {            
          return scannerService.getDocumentData(documentId);
      }
      
    2. ScannerService Interface

      byte[] getDocumentData (Long documentId) throws IOException, DocumentException;
      
    3. ScannerService Implementation – this renders PDF as well convert image into PDF for viewing

      @Override
      public byte[] getDocumentData(Long documentId) throws IOException, DocumentException
      {
          Document document = documentRepository.findById(documentId).get();
          Path documentPath = Paths.get(uploadPath + document.getDocumentPath());
      
          if(document.getDocumentExtension().contains("png")) {
              Image image = Image.getInstance(Files.readAllBytes(documentPath));
              float height = image.getHeight();
              float width = image.getWidth();
              String tmpdir = Files
                              .createTempDirectory("DmsCache")
                              .toFile()
                              .getAbsolutePath();
              System.out.println(tmpdir);
              com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
      
              Rectangle pageSize = new Rectangle(width,height);
              doc.setPageSize(pageSize);
              PdfWriter.getInstance(doc, new FileOutputStream(tmpdir+"/doc.pdf"));
      
              doc.open();
              doc.add(image);
              doc.close();
      
              Path tempPath = Paths.get(tmpdir+"/doc.pdf");
              byte[] documentData = Files.readAllBytes(tempPath);
              System.out.println("Img");
              return documentData;
          }
          else {
              byte[] documentData = Files.readAllBytes(documentPath);
              System.out.println("Pdf");
              return documentData;
          }
      
      }
      
    4. My JavaScript call method to dynamically render different files and embed into frame

      function readDocument(x){
          console.log(x.parentElement);
          console.log(x.parentElement.children);
          var documentId = x.parentElement.children.item(1).textContent;
      
          var urlDoc = 'http://localhost:8080/data/documentExplore/' + documentId;
          var viewElement = document.getElementById("dockit");
          viewElement.children.item(0).remove();
      
          var newObjectEl = document.createElement("embed");
          newObjectEl.type="application/pdf"
          newObjectEl.src=urlDoc.valueOf();
          newObjectEl.width="100%"
          newObjectEl.height="100%"
      
          viewElement.append(newObjectEl);
      }
      
    5. HTML embed tag to embed the rendered PDF into webpage:

      <div class="window-main-body" id="dockit">
          <embed
              type="application/pdf"
              src=""
              width="100%"
              height="100%"
          >
      </div>
      
    6. Due to security reason, embedding is generally disabled for which we have to manually configure these setting into spring boot:

      .and().headers().frameOptions().sameOrigin().and()
      

      The above should be added to Security Filter Chain in security configuration.


  2. <a href="file.pdf">PDF</a>, simply set up an anchor tag like this, you can also add up a button in between or keep the plain text. Now, when your PDF text is clicked, your pdf document shall open in pdf format

    mail me at [email protected] for further queries 🙂

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