How to use pdf-designer.js

[Table of contents]

1. Combine of PDF
2. Split(extraction) of PDF
3. Remove of PDF
4. Rotation of PDF
5. Add Bookmark of PDF
6. Property & Display settings of PDF
7. Overview of each class
8. Details of each class
    TPDFAnalyst
    * TPDFParser
    * TPDFCode
    TPDFDocInfo
    TPDFDocView
    * TReadStream
    * TMemoryStream
    * TFileStream
    TPDFCombine
    TPDFKnife
    TPDFDeletePage
    TPDFRotatePage
    TPDFInfoMaker
    TPDFOutLineMaker
    TPDFPageLayout
    TPDFPageMode
    TPDFOpenActionType
    TPDFOpenAction
    TPDFViewerPreferences
    TPDFNode
    TPDFNodeList
    TPDFOutLineManager
    TColor
    TRect
9. Common Functions
10. Callback function

First

You download pdf-designer.js, and install in your environment.

1. Combine of PDF

Important code is method of 22 line TPDFAnalyst.LoadFromStream(), and 52 line of TPDFCombine.SaveToFile()

TPDFAnalyst reads a PDF file. TPDFCombine combines the PDF files.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="pdf-designer.js" type="text/javascript"></script>
<script type="text/javascript">
var Analysts = new Array();    

function onChangeFile(event,index) {
    var reader = new FileReader();
    var file = event.target.files;
    
    document.getElementById("errmsg").innerHTML = '';
    
    reader.onload = function (event) {
        var Stream = new Uint8Array(reader.result);
        
        Analysts[index] = new TPDFAnalyst();
        
        try {
          
            Analysts[index].LoadFromStream(Stream);
            
            if (Analysts[index].Encrypt) {
                document.getElementById("p"+(index+1)).innerHTML =
                   'No' + (index+1) + ' PDF File - Unsupported';
                document.getElementById("errmsg").innerHTML = 
                   'It does not support encrypted files.';
            } else {
                document.getElementById("p"+(index+1)).innerHTML = 
                   'No' + (index+1) + ' PDF File - [' + Analysts[index].PageCount +
                    ' Pages / PDF' + Analysts[index].Version + ']';
            }
        } catch (e) {
            Analysts[index] = null;
            document.getElementById("p"+(index+1)).innerHTML =
               'No' + (index+1) + ' PDF File - Unsupported';      
            document.getElementById("errmsg").innerHTML =
               'No' + (index+1) +' PDF File is Not supported.';
        }
    }
    reader.readAsArrayBuffer(file[0]);
}

function run() {        
    var PDFCombine = new TPDFCombine();

    if (Analysts[0] != null && Analysts[1] != null) {
        try {
          
            // PDF_GetDateTime_Now() return the current date and time.
            PDFCombine.SaveToFile(PDF_GetDateTime_Now() + '.pdf', Analysts);
            
        } catch (e) {
            Analysts[0] = null;
            Analysts[1] = null;
            
            document.getElementById("errmsg").innerHTML = 
              'failed in the convert of the PDF file.';
        }
    } else {
        document.getElementById("errmsg").innerHTML =
          'Two PDF files, please select.';
    }
}
</script>
</head>
<body>
<h1>Combine of PDF</h1>
<hr>
<p>Two PDF files, please select.</p>
<p id="errmsg" style="color:red;"></p>   
<p id="p1">No1 PDF File</p>
<input type="file" id="inputfile1" accept="application/pdf" onchange="onChangeFile(event,0)"><br>
<p id="p2">No2 PDF File</p>
<input type="file" id="inputfile2" accept="application/pdf" onchange="onChangeFile(event,1)"><br>
<br>
<br>
<br>
<button id="run" style="width:200px;height:30px;" onclick="run();">Start Convert</button>
</body>
</html>

FileReader() is read the file asynchronously. Use the FileReaderSync() If you read in synchronization, in Worker object. These are the new features of HTML5.

Use class : TPDFAnalyst TPDFCombine

2. Split(extraction) of PDF

The following code to extract the first page of the PDF file.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="pdf-designer.js" type="text/javascript"></script>
<script type="text/javascript">
var Analyst = null;    

function onChangeFile(event) {
    var reader = new FileReader();
    var file = event.target.files;
    
    document.getElementById("errmsg").innerHTML = '';
    
    reader.onload = function (event) {
        var Stream = new Uint8Array(reader.result);
        
        Analyst = new TPDFAnalyst();
        
        try {
          
            Analyst.LoadFromStream(Stream);
            
            if (Analyst.Encrypt) {
                document.getElementById("p1").innerHTML = 'PDF File - Unsupported';
                document.getElementById("errmsg").innerHTML = 
                   'It does not support encrypted files.';
            } else {
                document.getElementById("p1").innerHTML = 
                    'PDF File - [' + Analyst.PageCount +
                    ' Pages / PDF' + Analyst.Version + ']';
            }
        } catch (e) {
            Analyst = null;
                document.getElementById("p1").innerHTML = 'PDF File - Unsupported';    
            document.getElementById("errmsg").innerHTML = 'This File is Not supported.';
        }
    }
    reader.readAsArrayBuffer(file[0]);
}

function run() {        
    var PDFKnife = new TPDFKnife();

    if (Analyst != null) {
        try {
           
            PDFKnife.SaveToFile(PDF_GetDateTime_Now() + '.pdf', Analyst,1,1);
            
        } catch (e) {
            Analyst[0] = null;
            Analyst[1] = null;
            
            document.getElementById("errmsg").innerHTML = 
              'failed in the convert of the PDF file. ';
        }
    } else {
        document.getElementById("errmsg").innerHTML =
          'Please select a file.';
    }
}
</script>
</head>
<body>
<h1>Split(extraction) of PDF</h1>
<hr>
<p>Extract the first page.</p>
<p id="errmsg" style="color:red;"></p>   
<p id="p1"></p>
<input type="file" id="inputfile1" accept="application/pdf" onchange="onChangeFile(event)"><br>
<br>
<br>
<br>
<button id="run" style="width:200px;height:30px;" onclick="run();">Start</button>
</body>
</html>

Use class : TPDFAnalyst TPDFKnife

3. Remove of PDF

Remove the first page. Please select a more than one page PDF file.

var PDFDeletePage = new TPDFDeletePage();
PDFDeletePage.SaveToFile(PDF_GetDateTime_Now() + '.pdf', Analyst,1,1);

Use class : TPDFAnalyst TPDFDeletePage

4. Rotation of PDF

All of the pages will rotate right 90 degrees.

var PDFRotatePage = new TPDFRotatePage();
PDFRotatePage.SaveToFile(PDF_GetDateTime_Now() + '.pdf', Analyst,1,1,Analyst.PageCount);

Use class : TPDFAnalyst TPDFRotatePage

5. Add Bookmark of PDF

Add a bookmark of level 1 on all pages.

var PDFOutLineMaker = new TPDFOutLineMaker();

// Display settings (bookmark)
PDFOutLineMaker.View.PageMode = TPDFPageMode.pmUseOutlines;

// Adding a Root Node (parent node)
for (var i = 0; i < Analyst.PageCount; i++) {
   PDFOutLineMaker.OutLine.AddRoot((i+1) +' page', (1+i), 0, '', false, false, null);
}
                                                                                    
PDFOutLineMaker.SaveToFile(PDF_GetDateTime_Now() + '.pdf', Analyst);

Use class : TPDFAnalyst TPDFOutLineMaker

6. Property & Display settings of PDF

Change all of the document information. And makes the display settings on the thumbnail.

var PDFInfoMaker = new TPDFInfoMaker();

// Document information
PDFInfoMaker.Info.Title = 'Title';
PDFInfoMaker.Info.Subject = 'Subject';
PDFInfoMaker.Info.Author = 'Author';
PDFInfoMaker.Info.Keywords = 'Keywords';
PDFInfoMaker.Info.Creator = 'Creator';
PDFInfoMaker.Info.Producer = 'Producer';
PDFInfoMaker.Info.CreationDate = PDF_GetDateTime_Now();
PDFInfoMaker.Info.ModDate      = PDF_GetDateTime_Now();

// Display settings (thumbnail)
PDFInfoMaker.View.PageMode = TPDFPageMode.pmUseThumbs;
                                                                                    
PDFInfoMaker.SaveToFile(PDF_GetDateTime_Now() + '.pdf', Analyst);

Use class : TPDFAnalyst TPDFInfoMaker

7. Overview of each class

The main class is the class of TPDFAnalyst and various conversion. Class 22, Enum 3.

[Basic]

ClassUse
TPDFAnalystAnalyzes. PDF files must be read always in this class.
* TPDFParserParsing, Writing
* TPDFCodeCharacter code
TPDFDocInfoDocument properties
TPDFDocViewDisplay Settings

[Stream]

ClassUse
* TReadStreamRead-only stream
* TMemoryStreamRead-write stream
* TFileStreamWrite-only stream

[Various conversion]

ClassUse
TPDFCombineCombine,Merge
TPDFKnifeSplit,Extraction
TPDFDeletePageRemove
TPDFRotatePageRotate
TPDFInfoMakerProperty & Display settings
TPDFOutLineMakerAdd Bookmark

[Display Settings]

ClassUse
TPDFPageLayoutPage layout(Enum)
TPDFPageModePage mode(Enum)
TPDFOpenActionTypeDisplay magnification(Enum)
TPDFOpenActionDisplay magnification(Class)
TPDFViewerPreferencesWindow options, user interface options(Class)

[Bookmark]

ClassUse
TPDFNode"Node" for the bookmark
TPDFNodeList"NodeList" for the bookmark
TPDFOutLineManagerWrite bookmark

[Other]

ClassUse
TColorStore the RGB values
TRectStore the page size (MediaBox)

8. Details of each class

Each class, and Enum type detail. The default is green color.

[TPDFAnalyst]

PropertyUse
VersionPDF Version(String)
StreamStream(TReadStream)
ObjectCountObject Count(Int)
ObjectPosArray Array of the position of object(Array)
DeleteObjectDeleted Objects(Array)
XrefTableListXref Table list(Array)
EncryptEncryption(true/false)
OptimizeOptimized for Web(true/false)
TagTagged PDF(true/false)
PageCountPage Count(Int)
PageSizePage Size(TRect)
RootIDRoot ID(Int)
InfoIDInfo ID(Int)
MetadataIDMetadata ID(Int)
FirstPageIDFirstPage ID(Int)
FirstPagesIDFirstPages ID(Int)
OutlinesIDOutlines ID(Int)

MethodLoadFromStream(Uint8Array)
UseRead a PDF file
ArgumentUint8Array: 8-bit array of unsigned integer value(It is a JavaScript object. Pass a binary array of files)
ReturnNone

[TPDFParser]

It only used internally.

[TPDFCode]

It only used internally.

[TPDFDocInfo]

PropertyUse
TitleTitle(String)
SubjectSubject(String)
AuthorAuthor(String)
KeywordsKeywords(String)
CreatorApplication(String)
ProducerPDF Conversion(String)
CreationDateCreation Date(String)
ModDateMod Date(String)
TrappedTrapp(true/false)

MethodGetPDFDocInfo(TPDFAnalyst)
UseSet the property of class by obtaining the document properties from PDF files.
ReturnNone

Please update the ModDate when changing only the document information. May not be displayed normally in "Acrobat Reader" when do not update it. Probably think of is reading the cache.

[TPDFDocView]

PropertyUse
PageModeTPDFPageMode(Enum)
PageLayoutTPDFPageLayout(Enum)
OpenActionTPDFOpenAction
ViewerPreferencesTPDFViewerPreferences

MethodGetPDFDocView(TPDFAnalyst)
UseSet the property of class by get the display settings from PDF files.
ReturnNone

[TReadStream]

It only used internally.

[TFileStream]

It only used internally.

[TMemoryStream]

It only used internally.

[TPDFCombine]

PropertyUse
InfoTPDFDocInfo
ViewTPDFDocView

MethodSaveToFile(FileName,TPDFAnalyst of Array,CallBack)
UseCombine of PDF
ArgumentFileName: File name to download
TPDFAnalyst of Array: TPDFAnalyst of Array
CallBack: Callback function(Optional)
ReturnNone

[TPDFKnife]

PropertyUse
InfoTPDFDocInfo
ViewTPDFDocView

MethodSaveToFile(FileName,TPDFAnalyst,begin,end)
UseSplit(extraction) of PDF
Argumentbegin,end: Set the page number you want to extraction(1,2,3...N)
ReturnNone

[TPDFDeletePage]

PropertyUse
InfoTPDFDocInfo
ViewTPDFDocView

MethodSaveToFile(FileName,TPDFAnalyst,begin,end)
UseRemove of PDF
Argumentbegin,end: Set the page number you want to remove(1,2,3...N)
ReturnNone

[TPDFRotatePage]

MethodSaveToFile(FileName,TPDFAnalyst,Rotate,begin,end)
UseRotation of PDF
ArgumentRotate: Specify of 1-3 (1: Right 90 degrees 2: Left 90 degrees 3: 180 degrees)
begin,end: Set the page number you want to Rotation(1,2,3...N)
ReturnNone

[TPDFInfoMaker]

PropertyUse
InfoTPDFDocInfo
ViewTPDFDocView

MethodSaveToFile(FileName,TPDFAnalyst)
UseProperty & Display settings of PDF
ReturnNone

[TPDFOutLineMaker]

PropertyUse
InfoTPDFDocInfo
ViewTPDFDocView
OutLineTPDFOutLineManager

MethodSaveToFile(FileName,TPDFAnalyst)
UseAdd Bookmark of PDF. Add a node in OutLine property.
ReturnNone

[TPDFPageLayout]

EnumUse
plDefaultDefault
plSinglePageSingle page
plOneColumnContinuous page
plTwoColumnLeftFacing page(left)
plTwoColumnRightFacing page(right)

[TPDFPageMode]

EnumUse
pmDefaultDefault
pmUseNoneNone
pmUseOutlinesBookmark and page
pmUseThumbsThumbnail and page
pmFullScreenFull screen

[TPDFOpenActionType]

EnumUse
oaDefaultDefault
oaXYZDisplay magnification.
It is necessary to set the value of TPDFOpenAction.Zoom If you select this item
oaFitEntire display
oaFitHFit width
oaFitV(unused)
oaFitR(unused)
oaFitB(unused)
oaFitBHFit drawing area
oaFitBV(unused)

[TPDFOpenAction]

PropertyUse
Left(unused)
Top(unused)
Right(unused)
Bottom(unused)
ZoomSpecifying the display magnification. specify one of the 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 4, 8, 16. Default : -1
ObjectIDObject number of the page to display first. (Default: -1 First page is displayed)
GenerationIDGeneration number of the page to display first. Specified with the ObjectID property. (Default: -1 First page is displayed) Hint?
SubTypeTPDFOpenActionType(Enum)

[TPDFViewerPreferences]

PropertyUse
HideToolbarHide Toolbar(true/false)
HideMenubarHide Menubar(true/false)
HideWindowUIHide window controls(true/false)
FitWindowAdjust the window size to the page(true/false)
CenterWindowPlace the window in the middle of the screen(true/false)
DirectionBinding(right)(true/false)
DisplayDocTitleDisplay the title of the document(true/false)
NonFullScreenPageModeTPDFPageMode(After full screen) Default:pmDefault

[TPDFNode]

PropertyUse
PagePage number(1,2,3 ... N) (Int)
ShowPosCoordinate position of the page(Basic is 0 recommended) (Int)
CaptionBookmark title(String)
URLURL(Page property is valid at the time of -1. Click the bookmark to open the URL) (String)
LevelHierarchy level. Parent node level 0 Child-grandchild nodes can be up to Level 4 (Int)
ItalicItalic(true/false)
BoldBold(true/false)
ColorCaption Color(TColor) Specify a null if not needed
ParentParent node(TPDFNode)
ChildNodesChild node(TPDFNodeList)

MethodGet(Index)
UseGet the child node
ReturnTPDFNode

MethodAddChild(Caption, Page, ShowPos, URL, Bold, Italic, Color)
UseAdd a child node
ArgumentTPDFNode See the property
ReturnTPDFNode

MethodGetCount()
UseGet the number of child nodes
ReturnNumber of child nodes

MethodGetChildCount()
UseGet the total number of child node and a grandchild node
ReturnTotal number of child node and a grandchild node

[TPDFNodeList]

MethodGet(Index)
UseGet the node
ReturnTPDFNode

MethodAdd(Parent, Level, Caption, Page, ShowPos, URL, Bold, Italic, Color)
UseAdd a node
ArgumentTPDFNode See the property
ReturnTPDFNode

MethodGetCount()
UseGet the number of nodes
ReturnNumber of nodes

[TPDFOutLineManager]

PropertyUse
NodeList of the parent node(TPDFNodeList)

MethodGet(Index)
UseGet the parent node
ReturnTPDFNode

MethodAddRoot(Caption, Page, ShowPos, URL, Bold, Italic, Color)
UseAdd a parent node
ArgumentTPDFNode See the property
ReturnTPDFNode

MethodGetCount()
UseGet the number of the parent node
ReturnNumber of parent node

MethodGetNodeCount()
UseGet the total number of nodes of all (including parent-child-grandchild)
ReturnTotal number of all (including parent-child-grandchild)

[TColor]

PropertyUse
RedRed. numerical value of 0-255
GreenGreen. numerical value of 0-255
BlueBlue. numerical value of 0-255

Use the PDF_RGB() common function to generate this class.

[TRect]

PropertyUse
LeftLeft
TopTop
RightRight
BottomBottom

9. Common Functions

FunctionPDF_GetDateTime_Now()
UseGet the current time(yyyymmddhhmmss)
ReturnCurrent time

FunctionPDF_RGB(Red, Green, Blue)
UseReturn the TColor from RGB values
ArgumentRed, Green, Blue: numerical value of 0-255
ReturnTColor

10. Callback function

Functionfunction PDFCallBack(value, filepos, files){}
UseCallback function upon binding of the PDF file.
Argumentvalue: Current progress(Max 100)
filepos: Current file number(1,2,3...N)
files: Total number of files
ReturnNone

Hidden function

Here there may be a hidden method of functions and classes that are not introduced :-)

Advertisements