Thursday, January 11, 2018

mac hack howto: add number captions to series of images and make PDF via p5 and preview

For a reading group I had made a series of book-excerpt screenshots.

For ease of distribution, I knew I could open all the files in Mac's "Preview", then go to File | Print then "Save as PDF" in the PDF dropdown in the lower left of the dialog.

Having done that, I realized that it would be easier to talk about the pages if they were numbered. I went to my P5 boilerplate page and then made the code that follows.

I put all the images in a directory called "rightraw/" in the same folder as the p5 html. I couldn't dig up an easy way of reading the folder contents, so I went to the image directory and did a
ls *png > ../files.txt

(To load the page I had to run a baby webserver, like it says on the boilerplate page, otherwise the script can't load the files)

So nothing is rocketscience about this hack but I was pleased I was able to get it done and redo the Preview PDF trick before having to head out for the day. Some folks might get adept with ImageMagick or Photoshop macros or whatever, but p5 is a pretty good go-to for me.


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>addcaptions</title>
<script src="p5.js"></script>
<script>
var counter = 0;    
var files;
var fileprefix = 'rightraw/';
function setup(){
    var canvas = createCanvas(500, 500);
    canvas.parent("canvasParent");
    loadStrings("files.txt",kickOff);
    
};
function draw(){
    noLoop();
}
function kickOff(s){
    files = s;
    procNextImage();
}
function procNextImage(){
    if(counter >= files.length) return;
    loadImage(fileprefix+files[counter],showPic);
    counter++;
}

function showPic(img){
    resizeCanvas(img.width,img.height);
    image(img,0,0);
    text(""+counter,20,20);
    draw();
    saveCanvas(counter+".png");
    procNextImage();
}
</script>
</head>
<body>
  <div id="canvasParent"></div>
</body>

</html>

No comments:

Post a Comment