diff --git a/CNAME b/CNAME new file mode 100644 index 0000000..d6a2dfc --- /dev/null +++ b/CNAME @@ -0,0 +1 @@ +pdfmerge.me \ No newline at end of file diff --git a/LICENCE.txt b/LICENCE.txt new file mode 100644 index 0000000..44d9482 --- /dev/null +++ b/LICENCE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 BRADSEC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index de85123..6769e33 100644 --- a/README.md +++ b/README.md @@ -1 +1,26 @@ -# pdf-merger \ No newline at end of file +# PDFMerge + +PDFMerge is a web-based application for merging PDFs and images into a single document. It operates entirely client-side for maximum privacy, using JavaScript, HTML, and CSS. Built on the robust [PDF-LIB.js](https://pdf-lib.js.org/) library, PDFMerge offers efficient PDF generation and manipulation. It also leverages the HTML5 FileReader API for image handling, and basic GPS and date EXIF details from photos thanks to [ExifReader](https://github.com/mattiasw/ExifReader). Key features include: + +- Merging PDFs/Images: Combine PDFs with .jpg, .png, .webp, .gif. +- Image Optimisation: Automatic resizing and optimisation for PDF A4 page format. +- Privacy Focus: No server uploads, ensuring user data privacy. +- EXIF Data Integration for images/photos: Optionally add file names, SHA-256 hash, and GPS/date EXIF details. +- Customisable Watermarking: Add text watermarks with adjustable color and opacity. +- Browser Compatibility: Optimal in Google Chrome; functional in other browsers with potential limitations. + +## Try it out @ [pdfmerge.me](https://pdfmerge.me) + +## Screenshots +![PDFMerge Interface](screenshot.png) + + +## Known Limitations and Testing + +- **In-Browser Processing Constraints:** PDFMerge runs directly in your browser, using client-side resources. This approach guarantees data privacy and eliminates the need for server-side data transfer. However, it does limit performance to what your device and browser can handle. This is particularly noticeable with large image files. Image files are restricted to a maximum size of 50MB due to potential performance issues during resizing with the HTML5 FileReader method. For larger images, it's advisable to use external tools to reduce their size and resolution before using them with the PDFMerge application. In testing [Google Chrome](https://www.google.com.au/chrome/) was able to handle larger files sizes and also larger lists of files at once better than Firefox. Firefox on occassion would hang and timeout on the same file lists which Chrome could process. + +## Credits and Third-Party Licensing +- **[PDF-LIB.js](https://pdf-lib.js.org/)** by Andrew-Dillon | [MIT License](https://opensource.org/licenses/MIT) +- **[ExifReader](https://github.com/mattiasw/ExifReader)** by Mattias Wallander | [MPL-2.0 license](https://www.mozilla.org/en-US/MPL/2.0/) +- **Roboto Regular, Bold, and Black Fonts** by Christian Robertson | [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) + diff --git a/css/index.html b/css/index.html new file mode 100644 index 0000000..e69de29 diff --git a/css/reset.css b/css/reset.css new file mode 100644 index 0000000..5eee735 --- /dev/null +++ b/css/reset.css @@ -0,0 +1,154 @@ +/* Custom CSS Reset */ +/* Modified 10 DEC 2023 */ + +/* Box Sizing */ +*, +*::before, +*::after { + box-sizing: border-box; +} + +/* Base Styles */ +html { + line-height: 1.15; + -webkit-text-size-adjust: 100%; + -moz-text-size-adjust: none; + text-size-adjust: none; +} + +body { + margin: 0; + min-height: 100vh; + font-family: inherit; + -webkit-font-smoothing: antialiased; + color: black; + background: white; + line-height: 1.5; +} + +/* Typography */ +h1, +h2, +h3, +h4, +h5, +h6 { + margin: 0; + font-size: 1em; + font-weight: normal; + line-height: 1.1; +} + +/* Balance text wrapping on headings */ +h1, +h2, +h3, +h4 { + text-wrap: balance; +} + +p, +a, +ul, +ol, +li, +blockquote, +article, +main, +aside, +footer, +header, +section { + margin: 0; + padding: 0; + font: inherit; + font-size: 100%; + vertical-align: baseline; +} + +/* Media Defaults */ +img { + display: block; + max-width: 100%; + height: auto; +} + +/* List Styles */ +ul[role="list"], +ol[role="list"] { + list-style: none; +} + +/* Button and Input Styles */ +button, +input, +textarea, +select { + border: none; + background-color: transparent; + padding: 0; + font: inherit; +} + +a { + color: inherit; + text-decoration: none; + text-decoration-skip-ink: auto; +} + +button { + cursor: pointer; +} + +/* Additional Resets */ +table { + border-collapse: collapse; + border-spacing: 0; +} + +/* Override browser default styles */ +::-moz-selection, +::selection { + background-color: #b3d4fc; + color: #000000; + text-shadow: none; +} + +/* Additional Form Element Styles */ +button, +input, +optgroup, +select, +textarea { + font-family: inherit; + font-size: 100%; + line-height: 1.15; + margin: 0; +} + +button, +input { + overflow: visible; +} + +button, +select { + text-transform: none; +} + +button, +[type="button"], +[type="reset"], +[type="submit"] { + -webkit-appearance: button; +} + +/* Make sure textareas without a rows attribute are not tiny */ +textarea:not([rows]) { + min-height: 10em; +} + +/* Extra scroll margin for anchored elements */ +:target { + scroll-margin-block: 5ex; +} diff --git a/css/styles.css b/css/styles.css new file mode 100644 index 0000000..4cb73ca --- /dev/null +++ b/css/styles.css @@ -0,0 +1,636 @@ +:root { + /* Set standard colors used starting lightest at 1 to darker */ + --color-white: #ffffff; + --color-black: #000000; + --color-blue-1: #0071e3; + --color-blue-2: #005ab5; + --color-blue-3: #004085; + --color-cyan-1: #1fb2d3; + --color-cyan-2: #1787a0; + --color-red-1: #c44438; + --color-red-2: #913128; + --color-green-1: #529a4a; + --color-green-2: #3f7539; + --color-orange-1: #d76f24; + --color-orange-2: #ad5a1e; + --color-gray-1: #fafafa; + --color-gray-2: #ebebeb; + --color-gray-3: #bebebe; + --color-gray-4: #999999; + --color-gray-5: #666666; + --color-gray-6: #4e4e4e; + --color-gray-7: #303030; + --color-gray-8: #1d1d1d; + /* Base HTML */ + --bg-color: var(--color-white); + --font-color: var(--color-gray-8); + --font-color-footer: var(--color-gray-5); + --font-family: "Roboto", sans-serif; + --base-font-size: 1em; + --line-height: 1.4em; + /* Branding */ + --branding-font-color: var(--color-gray-8); + --branding-span-font-color: var(--color-gray-5); + --branding-span-bg-color: None; + --branding-font-size: 2.2em; + --branding-letter-spacing: -0.025em; + /* Link settings */ + --link-font-color: var(--color-blue-2); + --link-hover-color: var(--color-gray-6); + --link-active-color: var(--color-blue-3); + /* Hero text settings */ + --hero-font-size: 1.4em; + --hero-line-height: 1.4em; + --hero-letter-spacing: 0.05em; + /* Button settings */ + --button-padding: 18px 24px; + --button-border-radius: 4px; + --button-bg-color: var(--color-blue-1); + --button-hover-bg-color: var(--color-blue-2); + --button-active-bg-color: var(--color-blue-3); + --button-font-color: var(--color-gray-1); + --button-disabled-font-color: var(--color-gray-6); + --button-disabled-bg-color: var(--color-gray-4); + /* File list */ + --font-color-filelist: var(--color-gray-5); + --bg-color-filelist: var(--color-gray-2); + /* Drop area */ + --border-color-drop-area: var(--color-gray-3); + --font-color-drop-area: var(--color-gray-3); + /* Form settings */ + --form-input-font-color: var(--color-gray-6); + --form-input-border: None; + --form-textarea-border: 1px solid var(--color-gray-3); + --form-input-bg-color: var(--color-gray-2); + --form-placeholder-color: var(--color-gray-4); +} + +[data-theme="dark"] { + /* Base HTML */ + --bg-color: var(--color-gray-8); + --font-color: var(--color-gray-4); + --font-family: "Roboto", sans-serif; + /* Branding */ + --branding-font-color: var(--color-gray-2); + --branding-span-font-color: var(--color-gray-4); + /* File list */ + --font-color-filelist: var(--color-gray-3); + --bg-color-filelist: var(--color-gray-7); + /* Drop area */ + --border-color-drop-area: var(--color-gray-5); + --font-color-drop-area: var(--color-gray-5); + /* Form settings */ + --form-input-font-color: var(--color-gray-4); + --form-input-border: None; + --form-textarea-border: 1px solid var(--color-gray-3); + --form-input-bg-color: var(--color-gray-7); + --form-placeholder-color: var(--color-gray-4); +} + +body { + font-family: var(--font-family); + margin: 0; + padding: 15px; + color: var(--font-color); + background-color: var(--bg-color); + font-size: var(--base-font-size); + line-height: var(--line-height); +} + +header { + display: grid; + grid-template-columns: 1fr; + align-items: center; + justify-content: space-between; +} + +.header-top { + display: flex; + justify-content: space-between; + align-items: center; +} + +main { + color: var(--font-color-main); + font-size: var(--font-size-main); +} + +footer { + color: var(--font-color-footer); + font-size: var(--font-size-footer); +} + +#theme-switcher { + display: flex; + align-items: center; + justify-content: flex-end; + margin-right: 10px; + cursor: pointer; + margin: 0; +} + +#sun-icon, +#moon-icon { + display: none; + width: 24px; + height: 24px; + margin: 8px; +} + +.branding { + display: flex; + align-items: center; /* Aligns items vertically centered */ + padding: 20px 10px; + font-size: var(--branding-font-size); + letter-spacing: var(--branding-letter-spacing); + color: var(--branding-font-color); + border-radius: 5px; + font-weight: bold; +} + +.branding img { + margin-right: 10px; /* Adjust the spacing between the icon and the text */ +} + +.branding span { + color: var(--branding-span-font-color); + background-color: var(--branding-span-bg-color); +} + +.branding a, +.branding a:link, +.branding a:active, +.branding a:visited, +.branding a:hover, +.branding span a, +.branding span a:link, +.branding span a:active, +.branding span a:visited, +.branding span a:hover { + color: var(--branding-font-color); + text-decoration: none; +} + +.hero { + text-align: center; + font-size: var(--hero-font-size); + letter-spacing: var(--hero-letter-spacing); + line-height: var(--hero-line-height); + margin-bottom: 15px; + margin-top: 5px; +} + +.hero p { + margin: 0 auto; +} + +.wrapper { + margin: 0 auto; + max-width: 960px; +} + +h1 { + font-size: 2em; + line-height: 1.2em; +} + +p { + margin: 10px 5px; +} + +a, +a:link, +a:visited { + color: var(--link-font-color); + text-decoration: none; +} + +a:hover { + color: var(--link-hover-color); +} + +a:active { + color: var(--link-active-color); +} + +.bold { + font-weight: 600; +} + +.hidden { + display: none; +} + +.align-center { + text-align: center; +} + +.hidden { + display: none; +} + +/* Button styling */ + +.button, +button, +button[type="submit"] { + margin: 8px 4px 8px 0; + font-weight: 600; + text-align: center; + display: inline-block; + background-color: var(--button-bg-color); + color: var(--button-font-color); + padding: var(--button-padding); + border: none; + border-radius: var(--button-border-radius); + cursor: pointer; + font-size: 1em; +} + +/* Media query for small screens */ +@media (max-width: 768px) { + .button, + button, + button[type="submit"] { + display: block; + width: 100%; + margin: 4px 0; + } +} + +.button:hover, +button:hover, +#file-upload-label:hover { + background-color: var(--button-hover-bg-color); +} + +.button:active, +button:active { + background-color: var(--button-active-bg-color); + color: var(--button-font-color); + box-shadow: inset 0 4px 6px rgba(0, 0, 0, 0.125); +} + +.button[disabled], +button[disabled], +button[disabled]:hover { + background-color: var(--button-disabled-bg-color); + color: var(--button-disabled-font-color); + opacity: 0.65; + cursor: not-allowed; +} + +.button-outline, +.button-outline:hover, +.button-outline:hover { + background: none; + color: var(--color-blue-1); + border: 2px solid var(--color-blue-1); + padding: 12px 20px; +} + +/* Flash message banner */ + +.flash-banner-container { + color: var(--color-white); + padding: 10px 0; + margin: 8px 4px 8px 0; + font-weight: 600; + text-align: center; + padding: var(--button-padding); + display: none; + border-radius: 4px; +} + +.flash-banner-success { + color: var(--color-white); + background-color: var(--color-green-1); +} + +.flash-banner-danger { + color: var(--color-white); + background-color: var(--color-red-1); +} + +.flash-banner-warning { + color: var(--color-white); + background-color: var(--color-orange-1); +} + +.flash-banner-info { + color: var(--color-white); + background-color: var(--color-cyan-1); +} + + + +/* Progress bar */ + +#progress-container { + display: none; + margin: 20px 0 10px 0; +} + +#progress-bar { + width: 0; + height: 20px; + background-color: var(--color-blue-1); + transition: width 0.3s; +} + + +.small { + font-size: 0.8em; + line-height: 1.3em; +} + +/* Checkbox toggles */ + +.toggle-description { + color: var(--color-gray-5); + font-size: 0.8em; + line-height: 1.2em; +} + +.toggle-group { + display: flex; + align-items: center; + flex-wrap: wrap; + margin: 10px 0; +} + +.toggle-item { + display: flex; + align-items: center; + margin: 10px 15px 10px 0; +} + +.toggle-item label { + display: flex; + justify-content: space-between; + align-items: center; + margin-left: 10px; +} + +.switch { + position: relative; + display: inline-block; + width: 40px; + height: 20px; + margin-right: 10px; +} + +.switch input { + opacity: 0; + width: 0; + height: 0; +} + +.slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: var(--color-gray-3); + transition: 0.4s; + border-radius: 20px; +} + +.slider:before { + position: absolute; + content: ""; + height: 16px; + width: 16px; + left: 2px; + bottom: 2px; + background-color: #fafafa; + transition: 0.4s; + border-radius: 50%; +} + +input:checked + .slider { + background-color: var(--color-blue-1); +} + +input:focus + .slider { + box-shadow: 0 0 1px var(--color-blue-2); +} + +input:checked + .slider:before { + transform: translateX(20px); +} + +.slider.round { + border-radius: 20px; +} + +/* Custom spinner */ + +.spinner { + border: 4px solid rgba(255, 255, 255, 0.3); + border-top: 4px solid var(--color-blue-1); + border-radius: 50%; + width: 40px; + height: 40px; + animation: spin 1s linear infinite; + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + z-index: 999; + display: none; +} + +@keyframes spin { + 0% { + transform: translate(-50%, -50%) rotate(0deg); + } + 100% { + transform: translate(-50%, -50%) rotate(360deg); + } +} + +li[draggable="true"] { + cursor: move; +} + +.drag-over { + border: none; +} + +/* Form elements styling */ + +form { + margin: 0 auto; + max-width: 720px; +} + +input[type="text"], +input[type="email"], +input[type="number"], +textarea { + color: var(--form-input-font-color); + display: block; + background-color: var(--form-input-bg-color); + border: var(--form-input-border); + border-radius: 3px; + padding: 15px 16px; +} + +input[type="file"] { + display: none; +} + +textarea { + margin: 10px 0; + resize: none; +} + +textarea:focus { + outline: none; +} + +select { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + color: var(--form-input-font-color); + width: 100%; + padding: 0.5em; + background-color: var(--form-input-bg-color); + border: var(--form-input-border); + border-radius: 3px; + padding: 12px 16px; +} + +select::-ms-expand { + display: none; +} + + +/* App specific custom styles */ + +#file-input { + display: none; +} + +#drop-area { + margin: 8px 4px 8px 0; + border: 2px dashed var(--border-color-drop-area); + border-radius: 3px; + padding: 15px; + text-align: center; + margin-bottom: 30px; + color: var(--font-color-drop-area); + min-height: 150px; +} + +#drop-area.drag { + border-color: var(--color-green-1); +} + +#file-list { + margin: 0; + display: flex; + justify-content: center; +} + +#selected-files-list { + margin: 0; + list-style: none; + padding: 0; + display: flex; + flex-wrap: wrap; + gap: 5px; +} + +#selected-files-list li { + background-color: var(--bg-color-filelist); + color: var(--font-color-filelist); + display: flex; + align-items: center; + justify-content: flex-start; + padding: 10px; + word-break: break-word; +} + +#selected-files-list li span { + font-weight: bold; + margin-right: auto; + padding-right: 5px; +} + +#file-upload-label { + margin: 8px 4px 8px 0; + font-weight: 600; + text-align: center; + display: block; + background-color: var(--color-blue-1); + color: var(--color-gray-1); + padding: var(--button-padding); + border: none; + border-radius: 4px; + cursor: pointer; +} + +#file-link { + font-weight: bold; + margin: 0 auto; + text-align: center; + display: inline; +} + +.file-link { + background: none; + display: inline-flex; + align-items: center; + justify-content: flex-start; + padding: 10px; + word-break: break-word; +} + +.file-link span { + margin-right: auto; + padding-right: 5px; +} + +/* Flash on file add */ + +@keyframes flash-success { + 0%, 100% { + background: none; + } + 50% { + background-color: var(--color-green-1); + color: #ffffff; + } +} + +.flash-success { + animation: flash-success 1s ease; +} + +.watermark-description { + color: var(--color-gray-5); + font-size: 0.8em; + line-height: 1.2em; +} + +.watermark-group { + display: flex; + align-items: center; + flex-wrap: wrap; + margin: 10px 0; +} + +.watermark-item { + display: flex; + align-items: center; + margin: 10px 15px 10px 10px; +} + +.watermark-item label { + margin-right: 10px; +} diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..314358c Binary files /dev/null and b/favicon.ico differ diff --git a/fonts/LICENSE.txt b/fonts/LICENSE.txt new file mode 100644 index 0000000..75b5248 --- /dev/null +++ b/fonts/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/fonts/Roboto-Black.ttf b/fonts/Roboto-Black.ttf new file mode 100644 index 0000000..0112e7d Binary files /dev/null and b/fonts/Roboto-Black.ttf differ diff --git a/fonts/Roboto-Bold.ttf b/fonts/Roboto-Bold.ttf new file mode 100644 index 0000000..43da14d Binary files /dev/null and b/fonts/Roboto-Bold.ttf differ diff --git a/fonts/Roboto-Regular.ttf b/fonts/Roboto-Regular.ttf new file mode 100644 index 0000000..ddf4bfa Binary files /dev/null and b/fonts/Roboto-Regular.ttf differ diff --git a/images/android-chrome-192x192.png b/images/android-chrome-192x192.png new file mode 100644 index 0000000..0d10bc4 Binary files /dev/null and b/images/android-chrome-192x192.png differ diff --git a/images/android-chrome-512x512.png b/images/android-chrome-512x512.png new file mode 100644 index 0000000..90ab55b Binary files /dev/null and b/images/android-chrome-512x512.png differ diff --git a/images/apple-touch-icon.png b/images/apple-touch-icon.png new file mode 100644 index 0000000..2cd1279 Binary files /dev/null and b/images/apple-touch-icon.png differ diff --git a/images/favicon-16x16.png b/images/favicon-16x16.png new file mode 100644 index 0000000..d491aec Binary files /dev/null and b/images/favicon-16x16.png differ diff --git a/images/favicon-32x32.png b/images/favicon-32x32.png new file mode 100644 index 0000000..eb6d61a Binary files /dev/null and b/images/favicon-32x32.png differ diff --git a/images/pdfmerge-icon.png b/images/pdfmerge-icon.png new file mode 100644 index 0000000..eb6d61a Binary files /dev/null and b/images/pdfmerge-icon.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..01ab083 --- /dev/null +++ b/index.html @@ -0,0 +1,151 @@ + + + + + + + + + + + + PDFMERGE - Merge PDFs and images FREE. Quickly and securely in your browser. + + + + + + +
+
+
+
+
PDFMERGE
+
+ + + + + + + + + + + + + + + + + + + + + +
+
+
+ Merge PDFs, convert images to PDFs, or blend both with text watermarks—quickly and securely in your browser. No data uploads to servers, no ads, and no sign-up required. +
+
+
+
+ + +
+

Or drag and drop files here...

+
+
    +
    +
    + + +
    +
    +
    + + + +
    + + + + + + + + + + +
    + + diff --git a/js/fileHandling.js b/js/fileHandling.js new file mode 100644 index 0000000..0ebec06 --- /dev/null +++ b/js/fileHandling.js @@ -0,0 +1,193 @@ +import { formatFileSize, displayFlashMessage } from './utils.js'; + +const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB +const selectedFiles = []; +const addedFilesSet = new Set(); + +function handleFileInputChange(event) { + const fileInput = event.target; + const fileLink = document.getElementById("file-link"); + const spinner = document.getElementById("spinner"); + + fileLink.style.display = "none"; + spinner.style.display = "block"; + + Array.from(fileInput.files).forEach((file) => { + if (isSupportedFileType(file) && isNewFile(file)) { + addedFilesSet.add(file.name); + selectedFiles.push(file); + } + }); + + updateSelectedFilesList(); + spinner.style.display = "none"; +} + +function handleDropArea(event) { + event.preventDefault(); + event.target.classList.remove("drag"); + const spinner = document.getElementById("spinner"); + const fileLink = document.getElementById("file-link"); + + fileLink.style.display = "none"; + spinner.style.display = "block"; + + const newFiles = Array.from(event.dataTransfer.files).filter( + (file) => isSupportedFileType(file) && isNewFile(file) + ); + + newFiles.forEach((file) => { + if (!selectedFiles.some((f) => f.name === file.name)) { + selectedFiles.push(file); + } + }); + + updateSelectedFilesList(); + spinner.style.display = "none"; +} + +function isSupportedFileType(file) { + if (!file) return false; + const supportedExtensions = ["pdf", "jpg", "jpeg", "png", "gif", "webp"]; + const extension = file.name.split(".").pop().toLowerCase(); + return supportedExtensions.includes(extension); +} + +function isNewFile(file) { + if (!file) return false; + const fileAlreadyExists = selectedFiles.some((f) => f.name === file.name); + return ( + !fileAlreadyExists && + (file.size <= MAX_FILE_SIZE || file.type === "application/pdf") + ); +} + +function updateSelectedFilesList() { + const fileList = document.getElementById("selected-files-list"); + const fragment = document.createDocumentFragment(); + const fileMap = new Map(); + + const filteredFiles = selectedFiles.filter((file) => { + if (!isSupportedFileType(file) || fileMap.has(file.name)) { + return false; + } + fileMap.set(file.name, true); + return true; + }); + + selectedFiles.length = 0; + selectedFiles.push(...filteredFiles); + + filteredFiles.forEach((file, index) => { + const listItem = document.createElement("li"); + listItem.className = "flex-item"; + listItem.draggable = true; + listItem.id = `file-${index}`; + + listItem.addEventListener("dragstart", handleDragStart); + listItem.addEventListener("dragover", handleDragOver); + listItem.addEventListener("drop", handleDrop); + + const iconSpan = document.createElement("span"); + iconSpan.className = "material-icons-outlined"; + iconSpan.style.marginRight = "8px"; + const fileExtension = file.name.split(".").pop().toLowerCase(); + + if (["jpg", "jpeg", "webp", "gif", "png"].includes(fileExtension)) { + iconSpan.textContent = "image"; + } else if (fileExtension === "pdf") { + iconSpan.textContent = "description"; + } else { + iconSpan.textContent = "description"; + } + + const fileSize = formatFileSize(file.size); + + listItem.appendChild(iconSpan); + listItem.appendChild(document.createTextNode(`${file.name} (${fileSize})`)); + + fragment.appendChild(listItem); + }); + + fileList.innerHTML = ""; + fileList.appendChild(fragment); + + updateButtonVisibility(); + updateToggleItemVisibility(); +} + +function handleDragStart(e) { + e.dataTransfer.setData('text/plain', e.target.id); + e.dataTransfer.effectAllowed = "move"; +} + +function handleDragOver(e) { + e.preventDefault(); + e.dataTransfer.dropEffect = "move"; +} + +function handleDrop(e) { + e.preventDefault(); + const draggedItemId = e.dataTransfer.getData('text'); + const draggedItem = document.getElementById(draggedItemId); + const dropTarget = e.target.closest('li'); + + if (dropTarget && draggedItem !== dropTarget) { + const draggedIndex = parseInt(draggedItemId.split('-')[1]); + const targetIndex = parseInt(dropTarget.id.split('-')[1]); + + const itemToMove = selectedFiles[draggedIndex]; + selectedFiles.splice(draggedIndex, 1); + selectedFiles.splice(targetIndex, 0, itemToMove); + + updateSelectedFilesList(); + } +} + +function updateButtonVisibility() { + const convertButton = document.getElementById("convert-button"); + const resetButton = document.getElementById("reset-button"); + + if (selectedFiles.length > 0) { + convertButton.style.display = "inline-block"; + resetButton.style.display = "inline-block"; + } else { + convertButton.style.display = "none"; + resetButton.style.display = "none"; + } +} + +function updateToggleItemVisibility() { + const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp"]; + const hasImageFiles = selectedFiles.some((file) => { + const fileName = file.name.toLowerCase(); + return imageExtensions.some((ext) => fileName.endsWith(ext)); + }); + + const toggleImageItem = document.getElementById("image-details-toggle"); + const toggleWatermarkItem = document.getElementById("watermark-details-toggle"); + + toggleImageItem.style.display = hasImageFiles ? "block" : "none"; + toggleWatermarkItem.style.display = selectedFiles.length > 0 ? "block" : "none"; +} + +function resetFiles() { + selectedFiles.length = 0; + const fileList = document.getElementById("selected-files-list"); + fileList.innerHTML = ""; + const fileInput = document.getElementById("file-input"); + fileInput.value = ""; + updateButtonVisibility(); + updateToggleItemVisibility(); +} + +export { + handleFileInputChange, + handleDropArea, + updateSelectedFilesList, + resetFiles, + selectedFiles, + isSupportedFileType, + updateButtonVisibility, + updateToggleItemVisibility +}; \ No newline at end of file diff --git a/js/index.html b/js/index.html new file mode 100644 index 0000000..e69de29 diff --git a/js/main.js b/js/main.js new file mode 100644 index 0000000..e496bd7 --- /dev/null +++ b/js/main.js @@ -0,0 +1,51 @@ +import { handleFileInputChange, handleDropArea, resetFiles, updateButtonVisibility } from './fileHandling.js'; +import { convertToPDF } from './pdfProcessing.js'; +import { initWatermarkControls } from './watermark.js'; + +function initializeApp() { + const fileInput = document.getElementById("file-input"); + const dropArea = document.getElementById("drop-area"); + const convertButton = document.getElementById("convert-button"); + const resetButton = document.getElementById("reset-button"); + + fileInput.addEventListener("change", handleFileInputChange); + + dropArea.addEventListener("dragover", (e) => { + e.preventDefault(); + dropArea.classList.add("drag"); + }); + + dropArea.addEventListener("dragleave", () => { + dropArea.classList.remove("drag"); + }); + + dropArea.addEventListener("drop", handleDropArea); + + convertButton.addEventListener("click", convertToPDF); + resetButton.addEventListener("click", resetFiles); + + updateButtonVisibility(); + initWatermarkControls(); + loadCheckboxStates(); +} + +function loadCheckboxStates() { + const checkboxIds = [ + "print-image-details", + "print-image-page-numbers", + "print-image-hash", + "landscape-orientation" + ]; + + checkboxIds.forEach(id => { + const checkbox = document.getElementById(id); + const savedState = localStorage.getItem(id); + checkbox.checked = savedState === "true"; + + checkbox.addEventListener("change", function() { + localStorage.setItem(id, this.checked); + }); + }); +} + +document.addEventListener("DOMContentLoaded", initializeApp); \ No newline at end of file diff --git a/js/pdfProcessing.js b/js/pdfProcessing.js new file mode 100644 index 0000000..f5aa4d7 --- /dev/null +++ b/js/pdfProcessing.js @@ -0,0 +1,447 @@ +import { + formatDateTime, + sleep, + getFormattedCurrentDate, + displayFlashMessage, + formatFileSize, + hexToRgb +} from './utils.js'; + +import { + selectedFiles, + isSupportedFileType, + updateButtonVisibility, + updateToggleItemVisibility +} from './fileHandling.js'; + +import { addWatermarkToPage } from './watermark.js'; + +const TIMEOUT_DURATION = 60000; // 60 seconds +let currentPageIndex = 0; +let conversionTimeout; + +const paperDimensions = { + A0: [841, 1189], + A1: [594, 841], + A2: [420, 594], + A3: [297, 420], + A4: [210, 297], +}; + +async function convertToPDF() { + conversionTimeout = setTimeout(() => { + handleConversionTimeout(); + }, TIMEOUT_DURATION); + + try { + currentPageIndex = 0; + const { PDFDocument, rgb } = PDFLib; + + const pdfDoc = await PDFDocument.create(); + pdfDoc.registerFontkit(fontkit); + const regularFont = await loadFont(pdfDoc, 'fonts/Roboto-Regular.ttf'); + const boldFont = await loadFont(pdfDoc, 'fonts/Roboto-Bold.ttf'); + const blackFont = await loadFont(pdfDoc, 'fonts/Roboto-Black.ttf'); + + const spinner = document.getElementById("spinner"); + const progressContainer = document.getElementById("progress-container"); + spinner.style.display = "block"; + progressContainer.style.display = "block"; + + if (selectedFiles.length < 1) { + displayFlashMessage("Select at least one image to convert.", "warning"); + return; + } + + const BATCH_SIZE = 5; + const fileChunks = chunkArray(selectedFiles, BATCH_SIZE); + let processedFiles = 0; + + for (const chunk of fileChunks) { + await processFileChunk(chunk, pdfDoc, regularFont, boldFont); + processedFiles += chunk.length; + const progressBar = document.getElementById("progress-bar"); + progressBar.style.width = `${(processedFiles / selectedFiles.length) * 100}%`; + await sleep(500); + } + + if (isWatermarkEnabled()) { + const pages = pdfDoc.getPages(); + pages.forEach((page) => addWatermarkToPage(page, getWatermarkText(), blackFont)); + } + + const pdfBytes = await pdfDoc.save(); + displayFlashMessage("PDF Merge complete.", "success"); + prepareFileLink(pdfBytes); + } catch (error) { + console.error("Error during PDF conversion:", error); + displayFlashMessage(`An error occurred during PDF conversion: ${error.message}`, "danger"); + } finally { + resetConversionState(); + } +} + +async function loadFont(pdfDoc, fontPath) { + const fontResponse = await fetch(fontPath); + const fontBytes = await fontResponse.arrayBuffer(); + return await pdfDoc.embedFont(fontBytes); +} + +function chunkArray(array, size) { + const chunkedArr = []; + for (let i = 0; i < array.length; i += size) { + chunkedArr.push(array.slice(i, i + size)); + } + return chunkedArr; +} + +async function processFileChunk(chunk, pdfDoc, regularFont, boldFont) { + for (const file of chunk) { + if (!isSupportedFileType(file)) { + console.error(`Unsupported file type: ${file.name}`); + continue; + } + try { + const fileName = file.name; + const fileExtension = fileName.split(".").pop().toLowerCase(); + if (["jpg", "jpeg", "webp", "gif", "png"].includes(fileExtension)) { + await processImageFile(file, pdfDoc, regularFont, boldFont); + } else if (fileExtension === "pdf") { + await processPdfFile(file, pdfDoc); + } else { + throw new Error(`Unsupported file format: ${fileExtension}`); + } + } catch (error) { + console.error("Error processing file:", error); + } + } +} + +async function processImageFile(file, pdfDoc, regularFont, boldFont) { + const dataUrl = await resizeImageAndConvertToJPEG(file); + const imageBytes = Uint8Array.from(atob(dataUrl.split(",")[1]), (c) => c.charCodeAt(0)); + + const isLandscape = isLandscapeOrientation(); + let [pageWidth, pageHeight] = getSelectedPaperSize(); + if (isLandscape) { + [pageWidth, pageHeight] = [pageHeight, pageWidth]; + } + const page = pdfDoc.addPage([pageWidth, pageHeight]); + + const leftMargin = 30; + const topMargin = 40; + const rightMargin = pageWidth - 30; + const bottomMargin = pageHeight - 40; + + const image = await pdfDoc.embedJpg(imageBytes); + + if (shouldPrintImageDetails() || shouldPrintImagePageNumbers() || shouldPrintImageHash()) { + await addImageDetailsToPage(page, file, regularFont, boldFont, pageWidth, pageHeight); + } + + const imgDim = image.scaleToFit( + rightMargin - leftMargin, + bottomMargin - topMargin - (shouldPrintImageDetails() ? 100 : 0) + ); + + const xPosition = (rightMargin - leftMargin - imgDim.width) / 2 + leftMargin; + const yPosition = (bottomMargin - topMargin - imgDim.height) / 2 + topMargin; + + page.drawImage(image, { + x: xPosition, + y: yPosition, + width: imgDim.width, + height: imgDim.height, + }); +} + +async function processPdfFile(file, pdfDoc) { + const fileBytes = await file.arrayBuffer(); + const existingPdfDoc = await PDFLib.PDFDocument.load(fileBytes, { + ignoreEncryption: true, + }); + const copiedPages = await pdfDoc.copyPages(existingPdfDoc, existingPdfDoc.getPageIndices()); + copiedPages.forEach((page) => pdfDoc.addPage(page)); +} + +function estimateTextWidth(text, fontSize) { + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + context.font = `${fontSize}px Arial`; + return context.measureText(text).width; + } + +async function addImageDetailsToPage(page, file, regularFont, boldFont, pageWidth, pageHeight) { + const fontSize = 10; + const maxTextWidth = pageWidth - 60; // Accounting for left and right margins + const lineHeight = 14; + const textX = 30; // Left margin + let textY = pageHeight - 20; // Top margin + + if (shouldPrintImageDetails()) { + const imgDetails = await getImageDetails(file); + const imgGpsInfo = imgDetails.imgGpsInfo; + const imgDateTime = imgDetails.imgDateTime; + + textY -= lineHeight; + drawWrappedText(page, file.name, textX, textY, maxTextWidth, lineHeight, boldFont, fontSize, "#000000"); + + if (imgDateTime !== null) { + textY -= lineHeight; + drawWrappedText(page, formatDateTime(imgDateTime), textX, textY, maxTextWidth, lineHeight, regularFont, fontSize, "#000000"); + } + + if (imgGpsInfo) { + textY -= lineHeight; + drawWrappedText(page, `GPS (Lat, Long) ${imgGpsInfo}`, textX, textY, maxTextWidth, lineHeight, regularFont, fontSize, "#000000"); + } + } + + if (shouldPrintImageHash()) { + const imgHash = await calculateImageHash(file); + if (imgHash !== null) { + textY -= lineHeight; + drawWrappedText(page, `SHA-256: ${imgHash}`, textX, textY, maxTextWidth, lineHeight, regularFont, fontSize, "#000000"); + } + } + + if (shouldPrintImagePageNumbers()) { + const pageNumberText = `Image ${currentPageIndex + 1}`; + const pageNumberFontSize = 10; + const pageNumberWidth = estimateTextWidth(pageNumberText, pageNumberFontSize); + const pageNumberX = pageWidth - pageNumberWidth - 30; + const pageNumberY = 30; + + page.drawText(pageNumberText, { + x: pageNumberX, + y: pageNumberY, + size: pageNumberFontSize, + font: regularFont, + color: PDFLib.rgb(0, 0, 0), + }); + currentPageIndex++; + } +} + +async function resizeImageAndConvertToJPEG(file) { + return new Promise((resolve, reject) => { + if (!window.FileReader) { + return reject("FileReader API is not supported by your browser."); + } + + const reader = new FileReader(); + reader.onload = function (e) { + const img = new Image(); + img.onload = function () { + try { + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + + const isLandscape = isLandscapeOrientation(); + let [pageWidth, pageHeight] = getSelectedPaperSize(); + if (isLandscape) { + [pageWidth, pageHeight] = [pageHeight, pageWidth]; + } + + const widthMM = pageWidth / 2.83465; + const heightMM = pageHeight / 2.83465; + const maxWidthPixels = widthMM * (300 / 25.4); + const maxHeightPixels = heightMM * (300 / 25.4); + + let width = img.width; + let height = img.height; + const scalingFactor = Math.min( + maxWidthPixels / width, + maxHeightPixels / height + ); + width = width * scalingFactor; + height = height * scalingFactor; + + canvas.width = width; + canvas.height = height; + ctx.drawImage(img, 0, 0, width, height); + + const dataUrl = canvas.toDataURL("image/jpeg", 0.9); + img.src = ""; + canvas.remove(); + resolve(dataUrl); + } catch (error) { + console.error("Error in image processing:", error); + reject("Error during image processing."); + } + }; + img.onerror = () => { + reject("Error loading the image file."); + }; + img.src = e.target.result; + }; + reader.onerror = () => { + reject("Error reading the file."); + }; + reader.readAsDataURL(file); + }); +} + +function handleConversionTimeout() { + console.error("Conversion process timed out."); + displayFlashMessage("Conversion process took too long and was terminated.", "danger"); + setTimeout(resetPage, 3000); +} + +function resetConversionState() { + const spinner = document.getElementById("spinner"); + const progressContainer = document.getElementById("progress-container"); + const progressBar = document.getElementById("progress-bar"); + spinner.style.display = "none"; + progressContainer.style.display = "none"; + progressBar.style.width = "0%"; + clearTimeout(conversionTimeout); + document.getElementById("add-watermark").checked = false; + updateButtonVisibility(); + updateToggleItemVisibility(); +} + +function prepareFileLink(pdfBytes) { + const blob = new Blob([pdfBytes], { type: "application/pdf" }); + const blobUrl = URL.createObjectURL(blob); + const filename = `PDFMerge_${getFormattedCurrentDate()}.pdf`; + const fileSize = formatFileSize(blob.size); + const anchor = document.createElement("a"); + + anchor.href = blobUrl; + anchor.download = filename; + anchor.style.display = "none"; + document.body.appendChild(anchor); + anchor.click(); + + const fileLink = document.getElementById("file-link"); + fileLink.href = blobUrl; + fileLink.innerHTML = `picture_as_pdf${filename} (${fileSize})`; + fileLink.style.display = "block"; + + setTimeout(() => { + URL.revokeObjectURL(blobUrl); + fileLink.innerHTML = ""; + resetPage(); + }, 60000); +} + +function isLandscapeOrientation() { + return document.getElementById("landscape-orientation").checked; +} + +function getSelectedPaperSize() { + const [widthMM, heightMM] = paperDimensions.A4; // Default to A4 + const widthPoints = widthMM * 2.83465; + const heightPoints = heightMM * 2.83465; + return [widthPoints, heightPoints]; +} + +async function getImageDetails(file) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = async function (e) { + try { + const fileExtension = file.name.split(".").pop().toLowerCase(); + let imgGpsInfo = null, + imgDateTime = null, + tags = null; + + if (fileExtension !== "webp" && fileExtension !== "gif") { + tags = EXIF.readFromBinaryFile(e.target.result); + if (tags && tags.GPSLatitude && tags.GPSLongitude) { + const gpsLat = tags.GPSLatitude[0] + tags.GPSLatitude[1] / 60 + tags.GPSLatitude[2] / 3600; + const gpsLong = tags.GPSLongitude[0] + tags.GPSLongitude[1] / 60 + tags.GPSLongitude[2] / 3600; + imgGpsInfo = `${gpsLat.toFixed(6)}, ${gpsLong.toFixed(6)}`; + } + if (tags && tags.DateTimeOriginal) { + imgDateTime = tags.DateTimeOriginal; + } + } + resolve({ exifData: tags, imgGpsInfo, imgDateTime }); + } catch (error) { + console.error("Error in getImageDetails:", error); + reject("Error processing image details."); + } + }; + reader.onerror = () => { + reject("Error reading the file for image details."); + }; + reader.readAsArrayBuffer(file); + }); +} + +async function calculateImageHash(file) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = async function (event) { + try { + const arrayBuffer = event.target.result; + const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer); + const hashArray = Array.from(new Uint8Array(hashBuffer)); + const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + resolve(hashHex); + } catch (error) { + console.error("Error calculating image hash:", error); + reject(null); + } + }; + reader.onerror = () => reject(null); + reader.readAsArrayBuffer(file); + }); +} + +function drawWrappedText(page, text, x, y, maxWidth, lineHeight, font, fontSize, hexColor) { + const { r, g, b } = hexToRgb(hexColor); + const words = text.split(' '); + let line = ''; + + for (let n = 0; n < words.length; n++) { + const testLine = line + words[n] + ' '; + const testWidth = font.widthOfTextAtSize(testLine, fontSize); + + if (testWidth > maxWidth && n > 0) { + page.drawText(line, { + x: x, + y: y, + size: fontSize, + font: font, + color: PDFLib.rgb(r, g, b), + }); + line = words[n] + ' '; + y -= lineHeight; + } else { + line = testLine; + } + } + + page.drawText(line, { + x: x, + y: y, + size: fontSize, + font: font, + color: PDFLib.rgb(r, g, b), + }); +} + +function shouldPrintImageDetails() { + return document.getElementById("print-image-details").checked; +} + +function shouldPrintImagePageNumbers() { + return document.getElementById("print-image-page-numbers").checked; +} + +function shouldPrintImageHash() { + return document.getElementById("print-image-hash").checked; +} + +function isWatermarkEnabled() { + return document.getElementById("add-watermark").checked; +} + +function getWatermarkText() { + return document.getElementById("watermark-text").value || "PDFMerge"; +} + +export { convertToPDF }; \ No newline at end of file diff --git a/js/theme.js b/js/theme.js new file mode 100644 index 0000000..38fcede --- /dev/null +++ b/js/theme.js @@ -0,0 +1,49 @@ +(function () { + const theme = localStorage.getItem("theme") || "light"; + document.body.setAttribute("data-theme", theme); +})(); + +document.addEventListener("DOMContentLoaded", () => { + const themeSwitcher = document.getElementById("theme-switcher"); + + function setTheme(theme) { + const body = document.body; + const themeColorMeta = document.querySelector('meta[name="theme-color"]'); + const sunIcon = document.getElementById("sun-icon"); + const moonIcon = document.getElementById("moon-icon"); + + if (theme === "dark") { + body.setAttribute("data-theme", "dark"); + if (themeColorMeta) themeColorMeta.content = "#202020"; + if (sunIcon) sunIcon.style.display = "none"; + if (moonIcon) moonIcon.style.display = "block"; + } else { + body.setAttribute("data-theme", "light"); + if (themeColorMeta) themeColorMeta.content = "#FFFFFF"; + if (sunIcon) sunIcon.style.display = "block"; + if (moonIcon) moonIcon.style.display = "none"; + } + } + + function getCookieTheme() { + const cookie = document.cookie + .split("; ") + .find((row) => row.startsWith("theme=")); + return cookie ? cookie.split("=")[1] : null; + } + + const cookieTheme = getCookieTheme(); + const savedTheme = cookieTheme || localStorage.getItem("theme") || "light"; + setTheme(savedTheme); + + if (themeSwitcher) { + themeSwitcher.addEventListener("click", () => { + const body = document.body; + const currentTheme = body.getAttribute("data-theme"); + const newTheme = currentTheme === "dark" ? "light" : "dark"; + setTheme(newTheme); + localStorage.setItem("theme", newTheme); + document.cookie = `theme=${newTheme}; path=/; max-age=31536000`; + }); + } +}); \ No newline at end of file diff --git a/js/utils.js b/js/utils.js new file mode 100644 index 0000000..44777c9 --- /dev/null +++ b/js/utils.js @@ -0,0 +1,99 @@ +function formatFileSize(bytes) { + const sizes = ["Bytes", "KB", "MB", "GB", "TB"]; + if (bytes === 0) return "0 Byte"; + const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); + return Math.round(bytes / Math.pow(1024, i), 2) + " " + sizes[i]; +} + +function formatDateTime(dateTime) { + if (!dateTime) { + return ""; + } + + const standardizedDateTime = dateTime.replace( + /(\d{4}):(\d{2}):(\d{2})/, + "$1-$2-$3" + ); + + const options = { + day: "numeric", + month: "short", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }; + + const isValidDate = !isNaN(Date.parse(standardizedDateTime)); + + if (isValidDate) { + return new Date(standardizedDateTime).toLocaleString("en-US", options); + } else { + return "Invalid Date"; + } +} + +function estimateTextWidth(text, fontSize) { + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + context.font = `${fontSize}px Arial`; + return context.measureText(text).width; +} + +function hexToRgb(hex) { + // Remove the hash at the start if it's there + hex = hex.replace(/^#/, ''); + + // Parse the hex string + const bigint = parseInt(hex, 16); + const r = (bigint >> 16) & 255; + const g = (bigint >> 8) & 255; + const b = bigint & 255; + + // Return an object with r, g, b properties + return { r: r / 255, g: g / 255, b: b / 255 }; +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function getFormattedCurrentDate() { + const currentDate = new Date(); + return currentDate + .toISOString() + .replace(/:/g, "") + .replace(/-/g, "") + .replace(/\.\d+/, ""); +} + +function displayFlashMessage(message, type) { + const flashBannerContainer = document.querySelector( + ".flash-banner-container" + ); + + flashBannerContainer.classList.remove( + "flash-banner-success", + "flash-banner-danger", + "flash-banner-warning", + "flash-banner-info" + ); + + flashBannerContainer.classList.add(`flash-banner-${type}`); + flashBannerContainer.textContent = message; + flashBannerContainer.style.display = "block"; + + setTimeout(function () { + flashBannerContainer.style.display = "none"; + }, 5000); +} + +export { + formatFileSize, + formatDateTime, + estimateTextWidth, + hexToRgb, + sleep, + getFormattedCurrentDate, + displayFlashMessage, +}; \ No newline at end of file diff --git a/js/watermark.js b/js/watermark.js new file mode 100644 index 0000000..019f378 --- /dev/null +++ b/js/watermark.js @@ -0,0 +1,52 @@ +import { hexToRgb } from './utils.js'; + +function addWatermarkToPage(page, text, font) { + const watermarkColor = document.getElementById("watermark-color").value || "#000000"; + const watermarkOpacity = parseFloat(document.getElementById("watermark-opacity").value) || 0.5; + + const { r, g, b } = hexToRgb(watermarkColor); + const opacity = watermarkOpacity; + + const { width, height } = page.getSize(); + const fontSize = calculateWatermarkFontSize(width, height, text, font); + + const angleRadians = Math.atan(height / width); + const angleDegrees = angleRadians * (180 / Math.PI); + + const textWidth = font.widthOfTextAtSize(text, fontSize); + const x = (width - textWidth * Math.cos(angleRadians)) / 2; + const y = (height + textWidth * Math.sin(angleRadians)) / 2; + + page.drawText(text, { + x: x, + y: y, + size: fontSize, + font: font, + color: PDFLib.rgb(r, g, b), + rotate: PDFLib.degrees(-angleDegrees), + opacity: opacity, + }); +} + +function calculateWatermarkFontSize(pageWidth, pageHeight, text, font) { + let fontSize = 10; + let textWidth; + + do { + fontSize++; + textWidth = font.widthOfTextAtSize(text, fontSize); + } while (textWidth < pageWidth && fontSize < 100); + + return fontSize; +} + +function initWatermarkControls() { + const watermarkCheckbox = document.getElementById("add-watermark"); + const watermarkGroup = document.querySelector(".watermark-group"); + + watermarkCheckbox.addEventListener("change", function () { + watermarkGroup.style.display = this.checked ? "flex" : "none"; + }); +} + +export { addWatermarkToPage, initWatermarkControls }; \ No newline at end of file diff --git a/screenshot.png b/screenshot.png new file mode 100644 index 0000000..04b5717 Binary files /dev/null and b/screenshot.png differ