|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "os" |
| 7 | + "sort" |
| 8 | + |
| 9 | + "github.com/pdfcpu/pdfcpu/pkg/api" |
| 10 | + "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model" |
| 11 | + "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/types" |
| 12 | + "github.com/rmitchellscott/aviary/internal/security" |
| 13 | +) |
| 14 | + |
| 15 | +type imageInfo struct { |
| 16 | + ObjNr int |
| 17 | + Width int |
| 18 | + Height int |
| 19 | + Area int |
| 20 | + PageNr int |
| 21 | +} |
| 22 | + |
| 23 | +func main() { |
| 24 | + if len(os.Args) < 2 { |
| 25 | + fmt.Println("Usage: pdfbgremove <input.pdf> [output.pdf]") |
| 26 | + os.Exit(1) |
| 27 | + } |
| 28 | + |
| 29 | + inputPath := os.Args[1] |
| 30 | + outputPath := inputPath[:len(inputPath)-4] + "_cleaned.pdf" |
| 31 | + if len(os.Args) >= 3 { |
| 32 | + outputPath = os.Args[2] |
| 33 | + } |
| 34 | + |
| 35 | + removed, err := removeBackgroundImages(inputPath, outputPath) |
| 36 | + if err != nil { |
| 37 | + fmt.Fprintf(os.Stderr, "Error: %v\n", err) |
| 38 | + os.Exit(1) |
| 39 | + } |
| 40 | + |
| 41 | + fmt.Printf("Removed %d background image(s)\n", removed) |
| 42 | + fmt.Printf("Output saved to: %s\n", outputPath) |
| 43 | +} |
| 44 | + |
| 45 | +func removeBackgroundImages(inputPath, outputPath string) (int, error) { |
| 46 | + secureInput, err := security.NewSecurePathFromExisting(inputPath) |
| 47 | + if err != nil { |
| 48 | + return 0, fmt.Errorf("invalid input path: %w", err) |
| 49 | + } |
| 50 | + secureOutput, err := security.NewSecurePathFromExisting(outputPath) |
| 51 | + if err != nil { |
| 52 | + return 0, fmt.Errorf("invalid output path: %w", err) |
| 53 | + } |
| 54 | + |
| 55 | + inFile, err := security.SafeOpen(secureInput) |
| 56 | + if err != nil { |
| 57 | + return 0, fmt.Errorf("failed to open input PDF: %w", err) |
| 58 | + } |
| 59 | + defer inFile.Close() |
| 60 | + |
| 61 | + conf := model.NewDefaultConfiguration() |
| 62 | + ctx, err := api.ReadContext(inFile, conf) |
| 63 | + if err != nil { |
| 64 | + return 0, fmt.Errorf("failed to read PDF context: %w", err) |
| 65 | + } |
| 66 | + |
| 67 | + if err := api.OptimizeContext(ctx); err != nil { |
| 68 | + return 0, fmt.Errorf("failed to optimize PDF context: %w", err) |
| 69 | + } |
| 70 | + |
| 71 | + if err := ctx.EnsurePageCount(); err != nil { |
| 72 | + return 0, fmt.Errorf("failed to ensure page count: %w", err) |
| 73 | + } |
| 74 | + |
| 75 | + inFile.Seek(0, io.SeekStart) |
| 76 | + allImages, err := api.Images(inFile, nil, conf) |
| 77 | + if err != nil { |
| 78 | + return 0, fmt.Errorf("failed to get images from PDF: %w", err) |
| 79 | + } |
| 80 | + |
| 81 | + pageCount := len(allImages) |
| 82 | + fmt.Printf("Processing %d pages...\n", pageCount) |
| 83 | + |
| 84 | + removedCount := 0 |
| 85 | + |
| 86 | + for pageNum := 1; pageNum <= pageCount; pageNum++ { |
| 87 | + var pageImages []imageInfo |
| 88 | + for _, pageMap := range allImages { |
| 89 | + for objNr, img := range pageMap { |
| 90 | + if img.PageNr == pageNum { |
| 91 | + pageImages = append(pageImages, imageInfo{ |
| 92 | + ObjNr: objNr, |
| 93 | + Width: img.Width, |
| 94 | + Height: img.Height, |
| 95 | + Area: img.Width * img.Height, |
| 96 | + PageNr: pageNum, |
| 97 | + }) |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + if len(pageImages) < 2 { |
| 103 | + continue |
| 104 | + } |
| 105 | + |
| 106 | + sort.Slice(pageImages, func(i, j int) bool { |
| 107 | + return pageImages[i].Area < pageImages[j].Area |
| 108 | + }) |
| 109 | + |
| 110 | + smallest := pageImages[0] |
| 111 | + fmt.Printf("Page %d: removing background (%dx%d)\n", pageNum, smallest.Width, smallest.Height) |
| 112 | + |
| 113 | + if err := removeImageFromPage(ctx, pageNum, smallest.ObjNr); err != nil { |
| 114 | + fmt.Printf(" Warning: %v\n", err) |
| 115 | + continue |
| 116 | + } |
| 117 | + removedCount++ |
| 118 | + } |
| 119 | + |
| 120 | + if removedCount == 0 { |
| 121 | + fmt.Println("No background images to remove, copying file as-is") |
| 122 | + inFile.Seek(0, io.SeekStart) |
| 123 | + outFile, err := security.SafeCreate(secureOutput) |
| 124 | + if err != nil { |
| 125 | + return 0, fmt.Errorf("failed to create output file: %w", err) |
| 126 | + } |
| 127 | + defer outFile.Close() |
| 128 | + if _, err := io.Copy(outFile, inFile); err != nil { |
| 129 | + return 0, fmt.Errorf("failed to copy file: %w", err) |
| 130 | + } |
| 131 | + return 0, nil |
| 132 | + } |
| 133 | + |
| 134 | + outFile, err := security.SafeCreate(secureOutput) |
| 135 | + if err != nil { |
| 136 | + return 0, fmt.Errorf("failed to create output file: %w", err) |
| 137 | + } |
| 138 | + defer outFile.Close() |
| 139 | + |
| 140 | + if err := api.WriteContext(ctx, outFile); err != nil { |
| 141 | + return 0, fmt.Errorf("failed to write modified PDF: %w", err) |
| 142 | + } |
| 143 | + |
| 144 | + return removedCount, nil |
| 145 | +} |
| 146 | + |
| 147 | +func removeImageFromPage(ctx *model.Context, pageNr int, objNr int) error { |
| 148 | + pageDict, _, inheritedAttrs, err := ctx.PageDict(pageNr, true) |
| 149 | + if err != nil { |
| 150 | + return fmt.Errorf("failed to get page dict: %w", err) |
| 151 | + } |
| 152 | + |
| 153 | + var resDict types.Dict |
| 154 | + if inheritedAttrs != nil && inheritedAttrs.Resources != nil { |
| 155 | + resDict = inheritedAttrs.Resources |
| 156 | + } else { |
| 157 | + resDict = pageDict.DictEntry("Resources") |
| 158 | + } |
| 159 | + |
| 160 | + if resDict == nil { |
| 161 | + return fmt.Errorf("page %d has no Resources dictionary", pageNr) |
| 162 | + } |
| 163 | + |
| 164 | + xobjEntry, found := resDict.Find("XObject") |
| 165 | + if !found { |
| 166 | + return fmt.Errorf("page %d Resources has no XObject entry", pageNr) |
| 167 | + } |
| 168 | + |
| 169 | + var xobjDict types.Dict |
| 170 | + switch v := xobjEntry.(type) { |
| 171 | + case types.Dict: |
| 172 | + xobjDict = v |
| 173 | + case types.IndirectRef: |
| 174 | + deref, err := ctx.Dereference(v) |
| 175 | + if err != nil { |
| 176 | + return fmt.Errorf("failed to dereference XObject dict: %w", err) |
| 177 | + } |
| 178 | + var ok bool |
| 179 | + xobjDict, ok = deref.(types.Dict) |
| 180 | + if !ok { |
| 181 | + return fmt.Errorf("XObject is not a dictionary") |
| 182 | + } |
| 183 | + default: |
| 184 | + return fmt.Errorf("unexpected XObject type: %T", xobjEntry) |
| 185 | + } |
| 186 | + |
| 187 | + var keyToRemove string |
| 188 | + for key, val := range xobjDict { |
| 189 | + if indRef, ok := val.(types.IndirectRef); ok { |
| 190 | + if int(indRef.ObjectNumber) == objNr { |
| 191 | + keyToRemove = key |
| 192 | + break |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + if keyToRemove == "" { |
| 198 | + return fmt.Errorf("could not find XObject key for objNr %d", objNr) |
| 199 | + } |
| 200 | + |
| 201 | + xobjDict.Delete(keyToRemove) |
| 202 | + ctx.FreeObject(objNr) |
| 203 | + |
| 204 | + return nil |
| 205 | +} |
0 commit comments