Converting docx files to PDF in Angular 15 using the "docxjs" library: A step-by-step guide

I am currently utilizing the to generate some docx files and enable downloading, but I am faced with the challenge of converting these files into PDF format.

This is my current process:

public download(data: any): void {
    const documentCreator = new DocumentCreator();
    const doc = documentCreator.create(data);

    Packer.toBlob(doc).then((blob) => {
      console.log(blob);
      saveAs(
        blob,
        `Contract ${data.place} ${_moment(data.dateEvent).format('LL')}.docx`
      );
      console.log('Document created successfully');
      this.closeModalExport();
    });
  }

export class DocumentCreator {
  // tslint:disable-next-line: typedef
  public create(diary): Document {
   //Some paragraph and text
return document;
  }
}

However, I am seeking guidance on how to convert the generated blob into a PDF file.

I have attempted to directly convert it and change the blob type, but unfortunately, it did not yield the desired outcome:

let pdf = new Blob([blob], {type: 'application/pdf'});
saveAs(
        pdf,
        `Contract ${data.place} ${_moment(data.dateEvent).format('LL')}.pdf`
      );

Answer №1

Regrettably, the docx.js tool does not come equipped with a function to directly change a docx file into a PDF format. To achieve this conversion, you will have to leverage another library or API.

Answer №2

Converting between binary formats without using files can be a challenge, but there are ways to achieve it. One method involves utilizing an endpoint from the quoted question API, which is displayed on the left side of the screen. While the layout may seem a bit simplistic (with a hint of humor in its Roman Font), an alternative approach is presented on the right side – a single line conversion using Windows' own command line that unfortunately results in some loss of fidelity due to font substitutions.

To perform a similar conversion from DocX to PDF while maintaining both layouts and styles, consider using a DocX reader/writer. Among the most versatile options available (aside from genuine MS Office or its interop) are Open Office/Libre Office, serving as a cost-effective alternative.

Most methods for producing PDFs necessitate access to a file system, even if temporarily stored in memory. It's important to note that direct blob-to-blob conversions aren't feasible without involving a DocX reader and PDF writer in the process.

An API might support blob conversion by accepting and decompressing a File.docX, printing it to a compressed FILE.PDF, converting it back to a blob through another process. This procedure takes time but is achievable.

Various services offer such capabilities; one example is https://github.com/unoconv/unoconv.

HOWEVER

When comparing online Word and Libre Office conversions, pay close attention to the differences in details.

The Libre Office rendition lacks bullet points, alters the layout to span 2 pages rather than 1, and incorporates new fonts instead of the original ones. These discrepancies raise concerns, particularly regarding the file's reduced size and unexpected font replacements!

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 causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

Cypress automation script fails to trigger Knockout computed subscription

Within my setup, I have implemented two textboxes and a span to display the result. Date: <input data-bind="value: dateValue"/> Number: <input data-bind="value: dateValue"/> Result : <span data-bind="text: calculatedValue">Result Should ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

You can only use a parameter initializer within the implementation of a function or constructor

I recently started learning TypeScript and am currently using it for React Bricks. I've been working on rendering a 3D object with three.js, but I keep encountering the error mentioned above. I've attempted various solutions such as passing color ...

RouterModule is a crucial external component that is essential for integrating

If I have a very simple component that is part of an Angular component library, it might look like this: mycomponent.module.html <div> <a routerLink="/"> </div> mycomponent.component.ts import { Component, OnInit, Input } from &a ...

One of the interfaces in use is malfunctioning, despite being identical to the other interface in TypeScript

I have been working on the IDocumentFilingDto.ts file. import { DocumentOrigin } from "./IDocumentFilingDto"; export interface IDocumentFilingDtoGen { UniqueId?: any; Title?: string; DocumentId?: string; Binder?: any; Communi ...

Adding content in real-time at the current cursor position within a Contenteditable element using Angular

I have a contenteditable div where I am facing an issue with pasting text. Whenever I try to paste some text into the div, it always gets pasted at the end. I am using ViewChild to access the reference of the contenteditable div and utilizing innerText to ...

Guide on making a Mapped Type in TypeScript using dynamic generic parameters

I am working with an object that contains one or more PreparedStatement. I am looking to create a general type definition for this object. Is there a way to achieve this in code? type PreparedRequest<Input, Result> = { input: Input; result: Resul ...

Keys preset in TypeScript using keyof

I need a set of predefined keys, but users should not be restricted to only using those keys. type B = { a: string; b: number; } type T = keyof B | string; function someFunc(key: T) {} someFunc(); // key type is `T` In the scenario above, I am lo ...

Resetting Cross-Site Request Forgery (CSRF

Struggling to integrate Django's csrf with Angular 6? Check out this insightful thread I came across. It seems that Django changes the token on login, which makes sense as I can register and login using post requests but encounter issues posting after ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

What is the proper way to incorporate types in a universal function?

Encountering an issue with TypeScript while using a universal function export const createNewArray = <T>( arr: T[], keyId: keyof T, keyTitle: keyof T, ) : [] | TValue[] => { const arrayAfterMap = arr.map((item) => ({name: item[ ...

Is it feasible to use Angular 2 in conjunction with local storage and JWT implementation on IE9 and

Could someone please advise me on how to implement local storage in Angular2 for IE9 and above? I've attempted following this guide https://medium.com/@blacksonic86/angular-2-authentication-revisited-611bf7373bf9#.h42z63t9v, but my Angular 2 applicati ...

Next.js Version 13 - Unable to find solution for 'supports-color' conflict

Currently in the midst of developing a Next.js 13 app (with TypeScript) and utilizing the Sendgrid npm package. An ongoing issue keeps popping up: Module not found: Can't resolve 'supports-color' in '.../node_modules/debug/src' ...

Is it planned to include StencilJS as a development choice in Ionic?

I'm curious about the potential adoption of Stencil JS for developing mobile apps within the Ionic framework. When I mention "an option for developing," I'm referring to frameworks like NativeScript where developers can choose between Angular + ...

There seems to be a troublesome character in the Nuxt3 production server causing some issues

When submitting an HTML encoded text to the server, everything runs smoothly on the development environment. However, once it is deployed to a Netlify server, the same request triggers a 500 error and the server side logging middleware only recognizes a PO ...

Struggling to implement the proper authentication method with API in Ionic

Having an API for the login, but being new to Ionic is causing difficulty in creating the correct method for the login process. The service file is located here: providers/restapi/restapi.ts import { HttpClient } from '@angular/common/http'; im ...

How can I retrieve all values in an object in Angularfire2 without needing to reference the key of the parent object?

I am looking to retrieve every object listed under each date within a specific expense category from the Firebase Database. Under the Firebase structure: - expenses - food - 07-11-2016 //"I want every object in here" + -KX7A ...

Establish a public-facing link for a React component

After developing a React component that functions as a chatbot window, I am now looking for a way to make the opening button accessible across various websites and applications. My initial thought was to associate a URL with the button so that it can be ea ...

Angular onscroll event creating a parallax effect

I attempted to create a parallax effect using Angular and the OnScroll event, however, while scrolling, the text seems to be flickering. Is there a way to make the smooth rendering onscroll? Maybe through CSS alone? Here is the script I used: https://sta ...