每日一问—02如何实现PDF合并?

import PyPDF2

pdf_files = ['D:\\TJU\\1.pdf', 'D:\\TJU\\1.pdf']
pdf_writer = PyPDF2.PdfFileWriter()

for file_name in pdf_files:
    pdf_reader = PyPDF2.PdfFileReader(open(file_name, 'rb'))
    for page_num in range(pdf_reader.numPages):
        pdf_writer.addPage(pdf_reader.getPage(page_num))

with open('D:\\TJU\\merged_file.pdf', 'wb') as merged_file:
    pdf_writer.write(merged_file)

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

std::vector<std::string> pdf_files = {"D:\\TJU\\1.pdf", "D:\\TJU\\3.pdf"};

std::string read_pdf(std::string filename) {
    std::ifstream file(filename, std::ios::binary);
    std::stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

int main() {
    std::ofstream merged_file("D:\\TJU\\merged_file.pdf", std::ios::binary | std::ios::app);
    for (const auto& file_name : pdf_files) {
        std::string pdf_content = read_pdf(file_name);
        merged_file << pdf_content;
    }
    merged_file.close();
    return 0;
}

这段代码不能正确合并 PDF 文件,因为它只是将 PDF 文件作为二进制数据进行简单的拼接。PDF 文件具有特定的结构,不能直接拼接。要合并 PDF 文件,可以使用专门的库,如 C++ 的 PoDoFo 或者 Python 的 PyPDF2 

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

// 定义要合并的 PDF 文件列表
std::vector<std::string> pdf_files = {"D:\\TJU\\1.pdf", "D:\\TJU\\1.pdf", "D:\\TJU\\1.pdf"};

// 读取 PDF 文件的内容
std::string read_pdf(std::string filename)
{
    std::ifstream file(filename, std::ios::binary | std::ios::app);
    std::stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

int main()
{
    // 打开输出文件
    std::ofstream merged_file("D:\\TJU\\merged_file.pdf", std::ios::binary | std::ios::app);

    // 定义一个字符串变量,用于存储所有 PDF 文件的内容
    std::string all_pdf_content;

    // 循环遍历要合并的 PDF 文件列表
    for (const auto &file_name : pdf_files)
    {
        // 读取 PDF 文件的内容,并将其添加到 all_pdf_content 变量中
        all_pdf_content += read_pdf(file_name);
    }

    // 将 all_pdf_content 变量的值写入合并文件
    merged_file << all_pdf_content;

    // 关闭输出文件
    merged_file.close();
    std::cout << "PDF files merged successfully." << std::endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南叔先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值