-
Notifications
You must be signed in to change notification settings - Fork 170
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add watermarking example #244
Open
richard-kurtosys
wants to merge
1
commit into
galkahana:master
Choose a base branch
from
richard-kurtosys:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,174 @@ | ||
/* | ||
|
||
This example writes a transparent watermark/stamp across every page in the supplied pdf. | ||
It writes the watermark from the bottom left to the top right at the fontSize specified. | ||
If it is calculated that the text is too long to fit then the font size is reduced. | ||
|
||
|
||
Assistance from: | ||
https://github.com/galkahana/HummusJS/issues/242 | ||
https://github.com/AndreMocke91 | ||
https://github.com/richard-kurtosys | ||
|
||
*/ | ||
|
||
var hummus = require('../hummus'); | ||
|
||
var pdfWriter = hummus.createWriterToModify('./multipage.pdf', { | ||
modifiedFilePath: './multipage_watermarked.pdf', | ||
}); | ||
|
||
var font = pdfWriter.getFontForFile('./Arial.ttf'); | ||
var fontSize = 45; //Initial font size - may be decreased in getTextMatric if the text is too long to fit the diagonal. | ||
var watermarkText = "Watermark Text" | ||
var matrixCache = {}; | ||
var objectCache = {}; | ||
|
||
var pdfReader = hummus.createReader('./multipage.pdf'); | ||
var isEncrypted = pdfReader.isEncrypted(); | ||
|
||
for (var i = 0; i < pdfReader.getPagesCount(); ++i) { | ||
|
||
//Get page size [left, bottom, right, top] | ||
const pageDimensions = pdfReader.parsePage(i).getCropBox(); | ||
|
||
//calculate the text size and angle | ||
var result = getTextMatrix(matrixCache, watermarkText, font, 45, pageDimensions[2], pageDimensions[3], 0.1); | ||
const tmMatrix = result.tMatrix; | ||
matrixCache = result.matrixCache; | ||
|
||
result = createXObject(tmMatrix, objectCache, watermarkText, font, pageDimensions, pdfWriter); | ||
|
||
var xObject = result.xObject; | ||
objectCache = result.objectCache; | ||
|
||
|
||
//get the page from the pdf in a modifier context | ||
var pageModifier = new hummus.PDFPageModifier(pdfWriter, i); | ||
|
||
//Write the "page object" onto the existing pdf page. | ||
var modifier = pageModifier.startContext().getContext(); | ||
modifier.q() | ||
.cm(1, 0, 0, 1, 0, 35) // Set Current Matrix - scale to 100% (x and y), translate 0,35 | ||
.doXObject(xObject) | ||
.Q(); | ||
|
||
pageModifier.endContext().writePage(); | ||
|
||
} | ||
pdfWriter.end(); | ||
|
||
//Calculate the angle the text should be displayed at from bottom left. | ||
//This takes into consideration the orientation of the page - landscape vs portrait will have different angles from bottom left to top right. | ||
function getTextMatrix(matrixCache, text, font, fontSize, pageRight, pageTop) { | ||
|
||
pageTop = pageTop; | ||
pageRight = pageRight; | ||
let cachedMatrix = matrixCache[`${pageRight} ${pageTop}`]; | ||
|
||
if (cachedMatrix) { | ||
return { tMatrix: cachedMatrix, matrixCache: matrixCache };; | ||
} | ||
|
||
const hypot = Math.hypot(pageTop, pageRight); | ||
let angle = 0; | ||
let textDimensions = font.calculateTextDimensions(text, fontSize); | ||
let lesserFontSize = fontSize; | ||
|
||
while (textDimensions.width > hypot * 0.8) { | ||
fontSize--; | ||
lesserFontSize = fontSize; | ||
textDimensions = font.calculateTextDimensions(text, fontSize); | ||
} | ||
|
||
const textWidth = textDimensions.width; | ||
const textHeight = textDimensions.height; | ||
const diagonalOffset = (hypot - textWidth) / 2; | ||
|
||
angle = -(Math.atan(pageTop / pageRight)).toFixed(2); | ||
|
||
const rightOffset = (diagonalOffset * Math.sin(-angle)); | ||
const bottomOffset = (diagonalOffset * Math.cos(-angle)); | ||
|
||
let tMatrix = { | ||
a: Math.cos(angle), | ||
b: -Math.sin(angle), | ||
c: Math.sin(angle), | ||
d: Math.cos(angle), | ||
e: bottomOffset, | ||
f: rightOffset, | ||
lesserFontSize, | ||
} | ||
|
||
matrixCache[`${pageRight} ${pageTop}`] = tMatrix; | ||
|
||
return { tMatrix: tMatrix, matrixCache: matrixCache }; | ||
} | ||
|
||
|
||
/* Create the transparent graphic state with 0.5 transparency */ | ||
function createTransparencyObject(pdfWriter) { | ||
var objCxt = pdfWriter.getObjectsContext(); | ||
var gsId = objCxt.startNewIndirectObject(); | ||
var dict = objCxt.startDictionary() | ||
dict.writeKey("type"); | ||
dict.writeNameValue("ExtGState"); | ||
dict.writeKey("ca"); | ||
objCxt.writeNumber(0.5); | ||
objCxt.endLine(); | ||
objCxt.endDictionary(dict); | ||
return gsId; | ||
} | ||
|
||
|
||
// #242: Use xObjectForm to get the gsName (graphic state name) | ||
function assignGsStateToResource(xObject, gsId) { | ||
var resourcesDict = xObject.getResourcesDictinary(); // This is not a typo =~= | ||
return resourcesDict.addExtGStateMapping(gsId); | ||
} | ||
|
||
|
||
//Make an object once that can be reused on many pages | ||
function setXObject(xObject, gsName, font, tmMatrix, text) { | ||
xObject.getContentContext() | ||
.q() | ||
.gs(gsName) //Use the graphic state we created earlier | ||
.BT() // Begin Text | ||
.k(0, 0, 0, 0.3) // Set Color (CMYK, 0-1) | ||
.Tf(font, tmMatrix.lesserFontSize) // Set font and font size | ||
.Tm(tmMatrix.a, tmMatrix.b, tmMatrix.c, tmMatrix.d, tmMatrix.e, tmMatrix.f) // Set the text matrix to the angle calculated in getTextMatrix | ||
.Tj(text) // Write the text | ||
.ET() // End Text | ||
.Q(); | ||
} | ||
|
||
function createXObject(tmMatrix, objectCache, watermarkText, font, pageDimensions, pdfWriter) { | ||
|
||
//Check if we have created an object for this page size already | ||
let cachedObject = objectCache[`${pageDimensions[2]} ${pageDimensions[3]}`]; | ||
if (cachedObject) { | ||
return { xObject: cachedObject, objectCache: objectCache }; | ||
} | ||
|
||
//Get the correct text matrix to display the text diagnoally across the page from corner to corner | ||
//This caters for portrait, landscape and anything in between | ||
|
||
|
||
//Create the transparency object | ||
var gsId = createTransparencyObject(pdfWriter); | ||
|
||
//Create a "page object" that we can later assign the transparency object to | ||
var xObject = pdfWriter.createFormXObject(0, 0, pageDimensions[2], pageDimensions[3]); | ||
|
||
//Add the graphic state to the "page object" and get the name back | ||
var gsName = assignGsStateToResource(xObject, gsId); | ||
|
||
//Write the text to the "page object" | ||
setXObject(xObject, gsName, font, tmMatrix, watermarkText); | ||
pdfWriter.endFormXObject(xObject); | ||
|
||
//Save the page size object to the cache | ||
objectCache[`${pageDimensions[2]} ${pageDimensions[3]}`] = xObject; | ||
|
||
return { xObject: xObject, objectCache: objectCache }; | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Dont think this is necessary... my bad