Skip to content

Instantly share code, notes, and snippets.

@silicontrip
Created February 19, 2021 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silicontrip/b2bef4cc3ca8cd4ebcc83487a8c3b344 to your computer and use it in GitHub Desktop.
Save silicontrip/b2bef4cc3ca8cd4ebcc83487a8c3b344 to your computer and use it in GitHub Desktop.
QPDF test code
#include <CoreFoundation/CFString.h>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QPDFWriter.hh>
#include <Foundation/NSObjcRuntime.h>
#include <string>
int main (int argc, char* argv[])
{
QPDF qdoc;
qdoc.emptyPDF();
QPDFObjectHandle qObject = QPDFObjectHandle::parse("<< /test 2 /Count 0 /Kids [ ] /Type /Pages >>");
std::cout << qObject.unparse() << std::endl; // Correctly outputs the replacement object
QPDFObjectHandle old = qdoc.getObjectByID(2,0);
std::cout << old.unparse() << std::endl;
std::cout << old.unparseResolved() << std::endl;
QPDFWriter qpdfWriter(qdoc);
// qpdfWriter.setOutputFilename("before.pdf"); // this wrote correctly.
qpdfWriter.setOutputMemory();
qpdfWriter.write();
Buffer* qBuf = qpdfWriter.getBuffer();
unsigned char const* qBytes = qBuf->getBuffer();
CFStringRef cs = CFStringCreateWithBytes(NULL, qBytes, qBuf->getSize(), 0, false);
NSLog(@"%@",(NSString*)cs); // Outputs the PDF correctly
delete(qBuf);
qdoc.replaceObject(2,0,qObject);
qdoc.updateAllPagesCache(); // I thought this might help
QPDFObjectHandle newo = qdoc.getObjectByID(2,0);
std::cout << newo.unparse() << std::endl; // returns the correct indirect object "2 0 R"
std::cout << newo.unparseResolved() << std::endl; // returns the correctly replaced object
QPDFWriter qpdf2Writer(qdoc);
// qpdfWriter.setOutputFilename("after.pdf"); // This crashed, when I changed the code to write to files
qpdf2Writer.setOutputMemory();
qpdf2Writer.write();
Buffer* q2Buf = qpdf2Writer.getBuffer();
unsigned char const* q2Bytes = q2Buf->getBuffer();
CFStringRef c2s = CFStringCreateWithBytes(NULL, q2Bytes, q2Buf->getSize(), 0, false);
NSLog(@"%@",(NSString*)c2s); // returns the original (before replacement) PDF
return 0;
}
@jberkenbilt
Copy link

Line 46 (commented out) crashes because it should say qpdf2Writer instead of qpdfWriter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment