Skip to content

Commit

Permalink
add setPrinter & fitPage functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
yeasir01 committed Feb 1, 2024
1 parent 454bc89 commit 8ab6362
Show file tree
Hide file tree
Showing 7 changed files with 84 additions and 38 deletions.
1 change: 1 addition & 0 deletions docs/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Properties are applicable exclusively to models that support each respective fun
| color | boolean | false |Print in color.|
| mono | boolean | false |Print in monochrome.|
| continue | boolean | false |Front margin not output.|
| fitPage | boolean | false |Specify whether to adjust the size and position of objects in the template in accordance with layout changes resulting from media changes. If set to true, adjustments will be made; otherwise, if set to false or undefined, no adjustments will be applied..|

## Supported Export Extensions
| **Description** | **Extension** |
Expand Down
44 changes: 28 additions & 16 deletions src/BrotherSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Data,
PrintConfig,
ImageOptions,
Constructor,
} from "./types";
import {
openTemplate,
Expand All @@ -20,14 +21,17 @@ import {
printOut,
endPrint,
exportTemplate,
setPrinter,
} from "./adapter";

export default class BrotherSdk {
#ready: boolean;

templatePath: string;

exportDir: string;
printer: undefined | string;

exportDir: undefined | string;

// One mutation observer, regardless of instances.
static #observer: MutationObserver | undefined;
Expand Down Expand Up @@ -64,16 +68,14 @@ export default class BrotherSdk {
* The path for exporting generated templates.
* - Win path: "C:\\\path\\\to\\\your\\\"
* - Unix path: "/home/templates/"
* @param {String} [object.printer = undefined]
* The name of the printer used for printing. Specify the printer name, not the path.
* - Example: "Brother QL-820NWB"
*/
constructor({
templatePath,
exportDir,
}: {
templatePath: string;
exportDir?: string;
}) {
constructor({ templatePath, exportDir, printer }: Constructor) {
this.templatePath = templatePath;
this.exportDir = exportDir || "";
this.exportDir = exportDir;
this.printer = printer;
this.#ready = false;
this.#initialize();
}
Expand All @@ -86,12 +88,12 @@ export default class BrotherSdk {
return;
}

if (targetNode.classList.contains(className)) {
this.#ready = true;
if (BrotherSdk.#observer) {
return;
}

if (BrotherSdk.#observer) {
if (targetNode.classList.contains(className)) {
this.#ready = true;
return;
}

Expand Down Expand Up @@ -180,17 +182,27 @@ export default class BrotherSdk {
* @param {boolean} [config.continue = false]
* Combines with printing for the following DoPrint( ) so that it is a single print job.
* As a result, when the next DoPrints are called up, the front margins are not output.
* @param {boolean} [config.fitPage = false]
* Specify whether to adjust the size and position of objects in the template in accordance
* with layout changes resulting from media changes. If set to true, adjustments
* will be made; otherwise, if set to false or undefined, no adjustments will be applied.
*/
async print(data: Data, config?: PrintConfig): Promise<boolean> {
const { copies = 1, printName = "BPAC-Document", ...rest } = config || {};

const bitmaskNumber = getStartPrintOptions(rest);
const {
copies = 1,
printName = "BPAC-Document",
fitPage = false,
...opts
} = config || {};

await this.#isPrintReady();

const bitMask = getStartPrintOptions(opts);

await openTemplate(this.templatePath);
await setPrinter(this.printer, fitPage);
await populateObjectsInTemplate(data);
await startPrint(printName, bitmaskNumber);
await startPrint(printName, bitMask);
await printOut(copies);
await endPrint();
await closeTemplate();
Expand Down
46 changes: 29 additions & 17 deletions src/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
import * as bpac from "./vendor/bpac-v3.4";
import { Data, ObjectTypes } from "./types";

const doc = bpac.IDocument;
const Doc = bpac.IDocument;

export const openTemplate = async (path: string): Promise<boolean> => {
const isOpen:boolean = await doc.Open(path);
export const openTemplate = async (path: string): Promise<void> => {
const isOpen:boolean = await Doc.Open(path);

if (!isOpen) {
throw new Error("Failed to open the template file.");
}
};

export const setPrinter = async (printer: string | undefined, fitPage: boolean): Promise<void> => {
if (printer === undefined && fitPage === false) return;

if (printer === undefined && fitPage === true) {
throw new Error("To use fitPage, you must manually set the printer name.");
}

const isPrinter:boolean = await Doc.SetPrinter(printer, fitPage);

if (!isPrinter) {
throw new Error(
"Failed to open template file.",
`Failed to set the printer. The specified printer "${printer}" may not exist or is not accessible.`,
);
}

return true;
};

export const closeTemplate = async (): Promise<boolean> => {
const isClosed = await doc.Close();
const isClosed = await Doc.Close();

if (!isClosed) {
throw new Error("Failed to close template file.");
Expand All @@ -26,7 +38,7 @@ export const closeTemplate = async (): Promise<boolean> => {
};

export const startPrint = async (printName:string, bitmask:number): Promise<boolean> => {
const isStarted:boolean = await doc.StartPrint(printName, bitmask);
const isStarted:boolean = await Doc.StartPrint(printName, bitmask);

if (!isStarted) {
await closeTemplate();
Expand All @@ -37,18 +49,18 @@ export const startPrint = async (printName:string, bitmask:number): Promise<bool
};

export const printOut = async (copies: number): Promise<boolean> => {
const isPrinted:boolean = await doc.PrintOut(copies, 0);
const isPrinted:boolean = await Doc.PrintOut(copies, 0);

if (!isPrinted) {
await closeTemplate();
throw new Error("Failed to print out.");
throw new Error("Failed to print, please verify the printer name is correct for the template.");
}

return true;
};

export const endPrint = async () => {
const hasEnded:boolean = await doc.EndPrint();
const hasEnded:boolean = await Doc.EndPrint();

if (!hasEnded) {
await closeTemplate();
Expand All @@ -59,23 +71,23 @@ export const endPrint = async () => {
};

export const imageData = async (width:number, height:number): Promise<string> => {
const data = await doc.GetImageData(4, width, height);
const data = await Doc.GetImageData(4, width, height);
return data;
};

export const getPrinterName = async (): Promise<string> => {
const printerName: string = await doc.GetPrinterName();
const printerName: string = await Doc.GetPrinterName();
return printerName;
};

export const getPrinters = async (): Promise<string[]> => {
const obj = await doc.GetPrinter();
const obj = await Doc.GetPrinter();
const printers = await obj.GetInstalledPrinters();
return printers;
};

export const exportTemplate = async (type:number, dest:string, res:number): Promise<boolean> => {
const isExported:boolean = await doc.Export(type, dest, res);
const isExported:boolean = await Doc.Export(type, dest, res);

if (!isExported) {
await closeTemplate();
Expand All @@ -91,7 +103,7 @@ export const populateObjectsInTemplate = async (data: Data): Promise<boolean> =>
// eslint-disable-next-line no-restricted-syntax
for (const prop of keys) {
const value = data[prop];
const obj = await doc.GetObject(prop);
const obj = await Doc.GetObject(prop);

if (!obj) {
await closeTemplate();
Expand All @@ -113,7 +125,7 @@ export const populateObjectsInTemplate = async (data: Data): Promise<boolean> =>
await obj.SetData(0, value);
break;
case ObjectTypes.Barcode:
await doc.SetBarcodeData(0, value);
await Doc.SetBarcodeData(0, value);
break;
case ObjectTypes.ClipArt:
await obj.SetData(0, value, 0);
Expand Down
5 changes: 4 additions & 1 deletion src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ const optionBitmaskMap: { [key in keyof StartPrintOptions]: number } = {
continue: 0x40000000,
};

export const getAbsolutePath = (basePath: string, filePathOrFileName: string): string => {
export const getAbsolutePath = (
basePath: string | undefined,
filePathOrFileName: string,
): string => {
// eslint-disable-next-line no-useless-escape
const isPath = /^(.*[\\\/])([^\\\/]+)\.([^.]+)$/;

Expand Down
16 changes: 14 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
export type Data = Record<string, string | Date>;
export type Data = {
[key:string] : string | Date
};

export type Constructor = {
templatePath: string;
exportDir?: string;
printer?: string;
};

export type PrintOptions = {
copies?: number;
Expand All @@ -24,7 +32,11 @@ export type StartPrintOptions = {
continue?: boolean,
};

export type PrintConfig = PrintOptions & StartPrintOptions;
export type FitPage = {
fitPage: boolean;
};

export type PrintConfig = PrintOptions & StartPrintOptions & FitPage;

export type ImageOptions = {
width?: number;
Expand Down
6 changes: 4 additions & 2 deletions tests/browser/playground.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ const tag = new BrotherSdk({
exportDir: "C:/Users/YMH/Desktop/Exported Labels/",
});


const data = {
title: "Test Label",
date: new Date("1/1/23"),
barcode: "074608352052",
image: "C:/Users/YMH/Desktop/Storage Drive Files/Logos/Monogram/my-logo.png",
};
/* {autoCut: true, mirroring: true, specialTape:true} */

const printTag = async () => {
try {
const complete = await tag.print(data, { highResolution: true, autoCut:true });
//tag.printer = "Brother QL-820NWB";
const complete = await tag.print(data, { highSpeed: true, autoCut:true, fitPage: false });
console.log({ complete });
} catch (error) {
console.log({ error });
Expand Down
4 changes: 4 additions & 0 deletions tests/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ describe("Helpers", () => {
expect(() => getAbsolutePath()).to.throw(Error);
});

it("Should throw an error when only one arg is passed.", () => {
expect(() => getAbsolutePath(undefined, dir.fileName)).to.throw(Error);
});

it("Should combine path and filename (backslashes).", () => {
const result = getAbsolutePath(dir.winBase, dir.fileName);
expect(result).to.have.string("C:\\Templates\\label.lbx");
Expand Down

0 comments on commit 8ab6362

Please sign in to comment.