pdf2clip.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <windows.h>
  2. #include <stdio.h>
  3. #define CUSTOM_FORMAT RegisterClipboardFormatA("Portable Document Format")
  4. int main(int argc, char* argv[])
  5. {
  6. // PDF文件路径
  7. const char* pdffile = "file.pdf";
  8. if(2 == argc)
  9. pdffile = argv[1];
  10. // 打开剪贴板
  11. if (!OpenClipboard(NULL)) {
  12. printf("Failed to open clipboard.\n");
  13. return 1;
  14. }
  15. // 清空剪贴板
  16. EmptyClipboard();
  17. // 读取PDF文件到内存
  18. FILE* file = fopen(pdffile, "rb");
  19. if (!file) {
  20. printf("Failed to open file.\n");
  21. CloseClipboard();
  22. return 1;
  23. }
  24. // 获取文件大小
  25. fseek(file, 0, SEEK_END);
  26. size_t fileSize = ftell(file);
  27. fseek(file, 0, SEEK_SET);
  28. // 分配内存并读取文件内容
  29. void* pdfData = malloc(fileSize);
  30. if (!pdfData) {
  31. printf("Failed to allocate memory.\n");
  32. fclose(file);
  33. CloseClipboard();
  34. return 1;
  35. }
  36. fread(pdfData, 1, fileSize, file);
  37. fclose(file);
  38. // 将二进制数据写入剪贴板
  39. HGLOBAL hGlobal = GlobalAlloc(GHND, fileSize);
  40. if (!hGlobal) {
  41. printf("Failed to allocate global memory.\n");
  42. free(pdfData);
  43. CloseClipboard();
  44. return 1;
  45. }
  46. memcpy(GlobalLock(hGlobal), pdfData, fileSize);
  47. GlobalUnlock(hGlobal);
  48. if (!SetClipboardData(CUSTOM_FORMAT, hGlobal)) {
  49. printf("Failed to set clipboard data.\n");
  50. GlobalFree(hGlobal);
  51. free(pdfData);
  52. CloseClipboard();
  53. return 1;
  54. }
  55. // 关闭剪贴板
  56. CloseClipboard();
  57. printf("PDF binary data copied to clipboard using custom format.\n");
  58. // 不要忘记释放内存
  59. free(pdfData);
  60. return 0;
  61. }