Dashboard Temp Share Shortlinks Frames API

HTMLify

image to pdf in one click
Views: 324 | Author: amar
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
<!DOCTYPE html>
<html>
<head>
  <title>Image to PDF Converter</title>
  <style>
    #uploadBox {
      border: 2px dashed #aaa;
      padding: 20px;
      width: 320px;
      text-align: center;
      margin: 50px auto;
      border-radius: 10px;
      transition: border-color 0.3s ease;
    }
    #uploadBox.dragover {
      border-color: #333;
    }
    #fileList {
      margin-top: 20px;
      text-align: left;
      font-family: sans-serif;
      font-size: 14px;
      max-height: 150px;
      overflow-y: auto;
    }
    .fileItem {
      margin-bottom: 5px;
    }
    #realInput {
      display: none;
    }
    #customBtn, #convertBtn {
      background-color: #eee;
      padding: 8px 14px;
      border-radius: 5px;
      cursor: pointer;
      border: 1px solid #aaa;
      margin: 5px;
      display: inline-block;
    }
  </style>
</head>
<body>

<div id="uploadBox">
  <h3>Image to PDF Converter </h3>

  <div id="customBtn">Add image</div>
  <input type="file" id="realInput" accept="image/*" multiple>
  <div id="fileList"></div>
  <div id="convertBtn">Convert to PDF</div>
   <h5>by amar</h5>
</div>

<!-- Include jsPDF library from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
  const { jsPDF } = window.jspdf; // use the jsPDF namespace

  const uploadBox = document.getElementById('uploadBox');
  const realInput = document.getElementById('realInput');
  const customBtn = document.getElementById('customBtn');
  const fileList = document.getElementById('fileList');
  const convertBtn = document.getElementById('convertBtn');

  let allFiles = []; // store the selected image files

  function updateDisplay() {
    fileList.innerHTML = "";
    allFiles.forEach((file, index) => {
      let name = file.name.length > 20 ? file.name.slice(0, 20) + "..." : file.name;
      const sizeKB = (file.size / 1024).toFixed(2);
      const div = document.createElement("div");
      div.className = "fileItem";
      div.textContent = `${index + 1}. ${name} (${sizeKB} KB)`;
      fileList.appendChild(div);
    });
  }

  function addFiles(newFiles) {
    for (let i = 0; i < newFiles.length; i++) {
      allFiles.push(newFiles[i]);
    }
    updateDisplay();
  }

  customBtn.addEventListener("click", () => realInput.click());

  realInput.addEventListener("change", () => {
    addFiles(realInput.files);
    realInput.value = ""; // reset so the same file can be added again if needed
  });

  // Drag & Drop support
  uploadBox.addEventListener("dragover", (e) => {
    e.preventDefault();
    uploadBox.classList.add("dragover");
  });

  uploadBox.addEventListener("dragleave", () => {
    uploadBox.classList.remove("dragover");
  });

  uploadBox.addEventListener("drop", (e) => {
    e.preventDefault();
    uploadBox.classList.remove("dragover");
    addFiles(e.dataTransfer.files);
  });

  // Helper function to read a file as Data URL
  function readFileAsDataURL(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  }

  // Convert images to PDF, centering each image on the page.
  async function convertImagesToPDF() {
    if (allFiles.length === 0) {
      alert("Please add at least one image file.");
      return;
    }

    // Create a new PDF document in portrait A4 (default in jsPDF)
    const pdf = new jsPDF();

    // Get PDF page dimensions
    const pageWidth = pdf.internal.pageSize.getWidth();
    const pageHeight = pdf.internal.pageSize.getHeight();
    // Optional: define margin (in units of jsPDF default, usually mm)
    const margin = 10;

    for (let i = 0; i < allFiles.length; i++) {
      const file = allFiles[i];
      try {
        const dataUrl = await readFileAsDataURL(file);
        // Create an image object to get its natural width/height
        const img = new Image();
        await new Promise((resolve, reject) => {
          img.onload = resolve;
          img.onerror = reject;
          img.src = dataUrl;
        });

        // Calculate maximum width and height to fit within margins
        const maxImgWidth = pageWidth - 2 * margin;
        const maxImgHeight = pageHeight - 2 * margin;

        // Scale image to fit within max dimensions while preserving aspect ratio
        let imgWidth = img.width;
        let imgHeight = img.height;

        const widthRatio = maxImgWidth / imgWidth;
        const heightRatio = maxImgHeight / imgHeight;
        const scale = Math.min(widthRatio, heightRatio);

        imgWidth *= scale;
        imgHeight *= scale;

        // Calculate positions to center the image on the page
        const xPos = (pageWidth - imgWidth) / 2;
        const yPos = (pageHeight - imgHeight) / 2;

        // If not the first image, add a new page to the PDF
        if (i > 0) {
          pdf.addPage();
        }
        // Add the image, using JPEG format (you can also use PNG if needed)
        pdf.addImage(dataUrl, 'JPEG', xPos, yPos, imgWidth, imgHeight);
      } catch (error) {
        console.error('Error processing file:', file.name, error);
      }
    }

    // Save the generated PDF
    pdf.save("converted.pdf");
  }

  convertBtn.addEventListener("click", convertImagesToPDF);
</script>
</body>
</html>