Skip to content

文档 (Document)

一个 PDF document 对象可以由一个已有的 PDF 文件从文件路径、内存缓冲区、自定义实现的 ReaderCallback 对象、输入文件流中构建。然后调用 PDFDoc.load 或者 PDFDoc.startLoad 加载文档内容。PDF document 对象用于文档级操作,比如打开和关闭 PDF 文档,获取页面、元数据等。

从头开始创建一个 PDF 文档

以下代码示例演示如何创建一个新的没有任何页面的 PDF 文档。

c++
#include "include/pdf/fs_pdfdoc.h"

using namespace foxit;
using namespace common;
using namespace pdf;
...

PDFDoc doc();
c
#include "include/fs_basictypes_c.h"
#include "include/fs_pdfdoc_c.h"
...

FS_PDFDOC_HANDLE doc;
FSDK_PDFDoc_Create(&doc);
java
import static com.foxit.sdk.pdf.PDFDoc.*;
...

PDFDoc doc = new PDFDoc();
python
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    # replace with the python2 lib path
    site.addsitedir(‘../../../’)
    from FoxitPDFSDKPython2 import *
else:
    from FoxitPDFSDKPython3 import *
...
doc = PDFDoc()
objective-c
#include "FSPDFObjC.h"
...

FSPDFDoc* doc = [[FSPDFDoc alloc] init];
javascript
const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");

...
let doc = new FSDK.PDFDoc("Sample.pdf");
csharp
using foxit.pdf;
...
PDFDoc doc = new PDFDoc();

通过文件路径加载一个现有的 PDF 文档

c++
#include "include/pdf/fs_pdfdoc.h"

using namespace foxit;
using namespace common;
using namespace pdf;
...

PDFDoc doc("Sample.pdf");
ErrorCode error_code = doc.Load();
if (error_code!= foxit::e_ErrSuccess) return 0;
c
#include "include/fs_basictypes_c.h"
#include "include/fs_pdfdoc_c.h"
...

FS_PDFDOC_HANDLE doc;
FSDK_PDFDoc_Create0("Sample.pdf", &doc);
FSErrorCode error_code = FSDK_PDFDoc_Load(doc, NULL);
if (error_code!= e_FSErrSuccess) return 0;
java
import static com.foxit.sdk.pdf.PDFDoc.*;
import static com.foxit.sdk.common.Constants.e_ErrSuccess;
...

PDFDoc doc = new PDFDoc("sample.pdf");
int error_code = doc.load(null);
if (error_code != e_ErrSuccess)
    return;
python
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    # replace with the python2 lib path
    site.addsitedir(‘../../../’)
    from FoxitPDFSDKPython2 import *
else:
    from FoxitPDFSDKPython3 import *

...
doc = PDFDoc("Sample.pdf")
error_code = doc.Load("")
if error_code!= e_ErrSuccess:
    return 0
objective-c
#include "FSPDFObjC.h"
...

NSString* pdfpath = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"pdf"];
FSPDFDoc* doc = [[FSPDFDoc alloc] initWithPath:pdfpath];
FSErrorCode errorCode = [doc load:nil];
if (errorCode != FSErrSuccess) {
    return -1;
}
javascript
const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");

...
let doc = new FSDK.PDFDoc("Sample.pdf");
let error_code = doc.Load("");
if (error_code != FSDK.e_ErrSuccess) {
    return 1;
}
csharp
using foxit.pdf;
using foxit.common;
...

PDFDoc doc = new PDFDoc("Sample.pdf");
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;

通过内存缓冲区加载一个现有的 PDF文档

c++
#include "include/pdf/fs_pdfdoc.h"

using namespace foxit;
using namespace common;
using namespace pdf;
...

FILE* pFile = fopen(TEST_DOC_PATH"blank.pdf", "rb");
ASSERT_EQ(TRUE, NULL != pFile);
fseek(pFile, 0, SEEK_END);
long lFileSize = ftell(pFile);
char* buffer = new char[lFileSize];
memset(buffer, 0, sizeof(char)*lFileSize);
fseek(pFile, 0, SEEK_SET);
fread(buffer, sizeof(char), lFileSize, pFile);
fclose(pFile);
PDFDoc doc = PDFDoc(buffer, lFileSize);
ErrorCode error_code = doc.Load();
if (error_code!= foxit::e_ErrSuccess) return 0;
c
#include "include/fs_basictypes_c.h"
#include "include/fs_pdfdoc_c.h"
...

FILE* pFile = fopen(TEST_DOC_PATH"blank.pdf", "rb");
ASSERT_EQ(TRUE, NULL != pFile);
fseek(pFile, 0, SEEK_END);
long lFileSize = ftell(pFile);
char* buffer = malloc(lFileSize * sizeof(char));
memset(buffer, 0, sizeof(char)*lFileSize);
fseek(pFile, 0, SEEK_SET);
fread(buffer, sizeof(char), lFileSize, pFile);
fclose(pFile);
FS_PDFDOC_HANDLE doc;
FSDK_PDFDoc_Create1(buffer, lFileSize, &doc);
FSErrorCode error_code = FSDK_PDFDoc_Load(doc, NULL);
Free(buffer);
if (error_code!= e_FSErrSuccess) return 0;
java
import static com.foxit.sdk.pdf.PDFDoc.*;
import static com.foxit.sdk.common.Constants.e_ErrSuccess;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
...

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("sample.pdf"));
byte[] b = new byte[bis.available()];
bis.read(b);
PDFDoc doc = new PDFDoc(b);
error_code = doc.load(null);
if (error_code != e_ErrSuccess)
return;
python
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    # replace with the python2 lib path
    site.addsitedir(‘../../../’)
    from FoxitPDFSDKPython2 import *
else:
    from FoxitPDFSDKPython3 import *

...
file = open("blank.pdf", "rb")
if file == None:
    return 0
file.seek(0, os.SEEK_END)
file_size = file.tell()
buffer = file.read(file_size)
file.close()
doc = PDFDoc(buffer, file_size)
error_code = doc.Load()
if error_code!= e_ErrSuccess: 
    return 0
objective-c
#include "FSPDFObjC.h"
...
NSData* file_data = [NSData dataWithContentsOfFile:pdf_path];

FSPDFDoc* doc = [[FSPDFDoc alloc] initWithBuffer:file_data];
FSErrorCode errorCode = [doc load:nil];
if (errorCode != FSErrSuccess) {
    return -1;
}
javascript
const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");
const fs = require('fs');
const os = require('os');
const path = require('path');
const util = require('util');

...
const data = fs.readFileSync("blank.pdf");
const file_size = data.length;
const buffer = Buffer.alloc(file_size);
data.copy(buffer);
let doc = new FSDK.PDFDoc(buffer, file_size);
error_code = doc.Load("");
if (error_code != FSDK.e_ErrSuccess) {
    return;
}
csharp
using foxit;
using foxit.pdf;
using foxit.common;
...

byte[] byte_buffer = File.ReadAllBytes(input_file);
IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal(byte_buffer.Length);
try
{
    System.Runtime.InteropServices.Marshal.Copy(byte_buffer, 0, buffer, byte_buffer.Length);
    PDFDoc doc = new PDFDoc(buffer, (uint)byte_buffer.Length);
    error_code = doc.Load(null);
    if (error_code != ErrorCode.e_ErrSuccess) return;
    ...
}
catch (foxit.PDFException e)
{
    Console.WriteLine("Error:{0}", e.GetErrorCode());
}
catch (System.Exception e)
{
    Console.WriteLine(e.Message);
}
finally
{
    System.Runtime.InteropServices.Marshal.FreeHGlobal(buffer);
}
...

通过自定义实现的 ReaderCallback 对象加载一个现有的 PDF 文档

c++
#include "include/pdf/fs_pdfdoc.h"

using namespace foxit;
using namespace common;
using namespace pdf;
...

class CFSFile_Read : public ReaderCallback
{
public:
 CFSFile_Read():m_fileFP(NULL)
  ,m_bLargeFile(FALSE)
 {}

 ~CFSFile_Read() {}

 bool LoadFile(const wchar_t* wFilePath, bool bLargeFile = FALSE)
 {
  std::wstring strTemp(wFilePath);
  string bstrFilepath = wchar2utf8(strTemp.c_str(), strTemp.size());

  m_fileFP = fopen(bstrFilepath.c_str(), "rb");
  if (!m_fileFP) return FALSE;

  m_bLargeFile = bLargeFile;
  return TRUE;
 }

 bool LoadFile(const char* filePath, bool bLargeFile = FALSE)
 {
  m_fileFP = fopen(filePath, "rb");
  if (!m_fileFP) return FALSE;

  m_bLargeFile = bLargeFile;
  return TRUE;
 }

 FILESIZE GetSize()
 {
  if (m_bLargeFile)
  {
#if defined(_WIN32) || defined(_WIN64)
   _fseeki64(m_fileFP, 0, SEEK_END);
   long long sizeL = _ftelli64(m_fileFP);
#elif defined(__linux__) || defined(__APPLE__)
   fseeko(m_fileFP, 0, SEEK_END);
   long long sizeL = ftello(m_fileFP);
#endif
   return sizeL;
  }
  else
  {
   fseek(m_fileFP, 0, SEEK_END);
   return (uint32)ftell(m_fileFP);
  }
 }

 int ReadBlock(void* buffer, FILESIZE offset, size_t size)
 {
  if (m_bLargeFile)
  {
#if defined(_WIN32) || defined(_WIN64)
   _fseeki64(m_fileFP, offset, SEEK_SET);
#elif defined(__linux__) || defined(__APPLE__)
   fseeko(m_fileFP, offset, SEEK_SET);
#endif
   long long readSize = fread(buffer, 1, size, m_fileFP);
   return (readSize == size);
  }
  else
  {
   if (!m_fileFP) return false;
   if(0 != fseek(m_fileFP, offset, 0))
    return false;
   if(0 == fread(buffer, size, 1, m_fileFP))
    return false;
   return true;
  }
 }

 size_t ReadBlock(void* buffer, size_t size) {
  if (m_bLargeFile)
  {
#if defined(_WIN32) || defined(_WIN64)
   _fseeki64(m_fileFP, 0, SEEK_SET);
#elif defined(__linux__) || defined(__APPLE__)
   fseeko(m_fileFP, 0, SEEK_SET);
#endif
   return fread(buffer, 1, size, m_fileFP);
  }
  else
  {
   if (!m_fileFP) return false;
   if(0 != fseek(m_fileFP, 0, 0))
    return 0;
   return fread(buffer, size, 1, m_fileFP);
  }
 }

 void Release()
 {
  if(m_fileFP)
   fclose(m_fileFP);
  m_fileFP = NULL;
  delete this;
 }

private:
 FILE* m_fileFP;
 bool m_bLargeFile;
}
...
string inputPDFPath = "Sample.pdf";
CFSFile_Read* pFileRead = new CFSFile_Read();
If(!pFileRead->LoadFile(inputPDFPath.c_str()))
 Return;
PDFDoc doc = PDFDoc(pFileRead);
ErrorCode error_code = doc.Load();
if (error_code!= foxit::e_ErrSuccess) return 0;
c
#include "include/fs_basictypes_c.h"
#include "include/fs_pdfdoc_c.h"
...

string wstring2string(const wchar_t *source, size_t source_size, char *dest, size_t dest_size) {
  char* curLocale = setlocale(LC_ALL, NULL);
  setlocale(LC_ALL, "chs");
  memset(_Dest, 0, _Dsize);
  wcstombs(dest, source, dest_size);
  setlocale(LC_ALL,”C”);
  return dest;
}

FILE* file = NULL;
FS_BOOL is_large_file = FALSE;

FS_INT64 gGetSize(void* user_data) {
  if (!user_data) return 0;
  if (is_large_file) {
    long long size_long;
    _fseeki64(file, 0, SEEK_END);
    size_long = _ftelli64(file);
    return size_long;
  } else {
   fseek(file, 0, SEEK_END);
   return (FS_INT64)ftell(file);
  }
  return 0;
}

FS_BOOL gReadBlock(void* user_data, void* buffer, FS_INT64 offset, size_t size) {
  if (is_large_file) {
    long long read_size;
    _fseeki64(file, offset, SEEK_SET);

    read_size = fread(buffer, 1, size, file);
    return read_size == size ? TRUE : FALSE;
  } else {
    if (!file)
      return FALSE;
    if (0 != fseek(file, (long)offset, 0))
      return FALSE;
    if (0 == fread(buffer, size, 1, file))
      return FALSE;
    return TRUE;
  }
  return FALSE;
}

static void gRelease(void* user_data) {
  if (file) {
    fclose(file);
    file = NULL;
  }  
  if (user_data)
   free(user_data);
}

...
const char* input_file = "Sample.pdf";
filereadercallback = (FSReaderCallback*)malloc(sizeof(FSReaderCallback));
filereadercallback->user_data = filereadercallback;
filereadercallback->GetSize = gGetSize;
filereadercallback->ReadBlock = gReadBlock;
filereadercallback->Release = gRelease;
_wfopen_s(&file, input_file, L"rb");
FS_PDFDOC_HANDLE doc;
FSDK_PDFDoc_Create3(pFileRead, &doc);
FSErrorCode error_code = FSDK_PDFDoc_Load(doc, NULL);
if (error_code!= e_FSErrSuccess) return 0;
java
import static com.foxit.sdk.pdf.PDFDoc.*;
import static com.foxit.sdk.common.Constants.e_ErrSuccess;
import java.io.IOException;
import com.foxit.sdk.common.fxcrt.FileReaderCallback;
import java.io.RandomAccessFile;
...

class FileReader extends FileReaderCallback {
    private RandomAccessFile file_ = null;
    FileReader() {
    }

    boolean LoadFile(String file_path) throws FileNotFoundException {
        file_ = new RandomAccessFile(file_path, "r");
        return true;
    }

    @Override
    public long getSize() {
     try {
            return this.file_.length();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public boolean readBlock(byte[] buffer, long offset, long size) {

        try {
            file_.seek(offset);
            int read = file_.read(buffer, 0, (int) size);
            return read == size ? true : false;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void release() {
        try {
            this.file_.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileReader callback = new FileReader();
callback.LoadFile("sample.pdf");
PDFDoc doc = new PDFDoc(callback, false);
int error_code = doc.load(null);
if (error_code != e_ErrSuccess) 
return;
python
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    # replace with the python2 lib path
    site.addsitedir(‘../../../’)
    from FoxitPDFSDKPython2 import *
else:
    from FoxitPDFSDKPython3 import *
...
class CFSFile_Read(FileReaderCallback):
    def __init__(self, *args):
        if _PYTHON2_:
            super(CFSFile_Read, self).__init__()
        else:
            super().__init__()
        self.file_ = None
        self.offset_ = args[0]

    def __del__(self):
        self.__disown__()

    def Release(self, *args):
        self.file_.close()

    def LoadFile(self, *args):
        self.file_ = open(args[0], "rb")
        if self.file_ is not None:
            return True
        else:
            return False

    def GetSize(self, *args):
        return self.offset_

    def ReadBlock(self, *args):
        if self.file_ is None:
            return False, None

        size = 0
        if len(args) == 2:
            self.file_.seek(args[0], 0)
            size = args[1]
        elif len(args) == 1:
            size = args[0]
        else:
            return False, None
        buffer = self.file_.read(size)
        return True, buffer
...
input_pdf_path = "Sample.pdf"
file_read = CFSFile_Read()
if not file_read.LoadFile(input_pdf_path):
    return
doc = PDFDoc(file_read)
error_code = doc.Load()
if error_code!= e_ErrSuccess:
    return 0
objective-c
#include "FSPDFObjC.h"
...

@interface FSFileRead : NSObject<FSFileReaderCallback>

- (id)initWithSourceFilePath:(NSString *)path offset:(long long)offset;

@end

@implementation FSFileRead {
    FileReader *imp;
}

- (id)initWithSourceFilePath:(NSString *)path offset:(long long)offset {
    if (self = [super init]) {
        imp = new FileReader(offset);
        if (!imp->LoadFile([path UTF8String])) {
            return nil;
        }
    }
    return self;
}

- (void)dealloc {
    delete imp;
}

- (unsigned long long)getSize {
    return imp->GetSize();
}

- (NSData *)readBlock:(unsigned long long)offset size:(unsigned long long)size {
    void *buffer = malloc(size);
    if (!buffer) {
        NSLog(@"failed to malloc buffer of size %llu", size);
        return nil;
    }
    if (imp->ReadBlock(buffer, offset, (size_t)size)) {
        return [NSData dataWithBytesNoCopy:buffer length:size];
    } else {
        free(buffer);
        return nil;
    }
}

@end

FSFileRead *file_reader = [[FSFileRead alloc] initWithSourceFilePath:file_name offset:offset];

FSPDFDoc *doc_real = [[FSPDFDoc alloc] initWithFile_read:file_reader is_async:NO];
FSErrorCode code = [doc_real load:nil];
if (code != FSErrSuccess) {
    return -1;
}
javascript
const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");
const fs = require('fs');
const os = require('os');
const path = require('path');
const util = require('util');
...

class FileReader {
    constructor() {
        this.file_ = null;
        this.file_path_ = "";
        this.hint_data_record_ = [];
    }

    LoadFile(file_path) {
        try {
            this.file_path_ = file_path;
            this.file_ = fs.openSync(file_path, 'r');
            return true;
        } catch (err) {
            console.error(err);
            return false;
        }
    }

    CloseFile() {
        fs.closeSync(this.file_);
    }

    GetSize() {
        try {
            let stats = fs.statSync(this.file_path_);
            return stats.size;
        } catch (err) {
            console.error(err);
            return 0;
        }
    }

    ReadBlock(offset, size_t) {
        try {
            let buffer = Buffer.alloc(size_t);
            fs.readSync(this.file_, buffer, 0, size_t, offset);
            return [true, buffer]
        } catch (err) {
            return [false, null];
        }
    }

    Release() {
    }
}

...
let input_pdf_path = "Sample.pdf";
let file_reader = new FileReader(offset);
file_reader.LoadFile(input_pdf_path);
let reader_callback = new FSDK.FileReaderCallback(file_reader);

let doc_real = new FSDK.PDFDoc(reader_callback, false);
code = doc.Load("");
if (code != FSDK.e_ErrSuccess) {
    return;
}
csharp
using foxit.pdf;
using foxit.common;
...

class FileReader : FileReaderCallback
    {
        private FileStream file_ = null;
        private long offset_ = 0;

        public FileReader(long offset)
        {
            this.offset_ = offset;
        }

        public Boolean LoadFile(String file_path)
        {
            file_ = new FileStream(file_path, FileMode.OpenOrCreate);
            return true;
        }

        public override long GetSize()
        {
            return this.offset_;
        }

        public override bool ReadBlock(IntPtr buffer, long offset, uint size)
        {
            int read_size = 0;
            file_.Seek(offset, SeekOrigin.Begin);
            byte[] array = new byte[size + 1];
            read_size = file_.Read(array, 0, (int)size);
            Marshal.Copy(array, 0, buffer, (int)size);
            return read_size == size ? true : false;
        }

        public override void Release()
        {
            this.file_.Close();
        }
    }
...

FileReader file_reader = new FileReader(offset);
file_reader.LoadFile(file_name);

PDFDoc doc_real = new PDFDoc(file_reader, false)

error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...

加载 PDF 文档以及获取文档的首页

c++
#include "include/pdf/fs_pdfdoc.h"
#include "include/pdf/fs_pdfpage.h"

using namespace foxit;
using namespace common;
using namespace pdf;
...

PDFDoc doc("Sample.pdf");
ErrorCode error_code = doc.Load();
if (error_code!= foxit::e_ErrSuccess) return 0;
PDFPage page = doc.GetPage(0);
page.StartParse(foxit::pdf::PDFPage::e_ParsePageNormal, NULL, false);
c
#include "include/fs_basictypes_c.h"
#include "include/fs_pdfdoc_c.h"
#include "include/fs_pdfpage_c.h"
...

FS_PDFDOC_HANDLE doc;
FSDK_PDFDoc_Create0("Sample.pdf", &doc);
FSErrorCode error_code = FSDK_PDFDoc_Load(doc, NULL);
if (error_code!= e_FSErrSuccess) return 0;
FS_PDFPAGE_HANDLE page;
FSDK_PDFDoc_GetPage(doc, 0, &page);
FS_PROGRESSIVE_HANDLE progressive;
FSDK_PDFPage_StartParse(page, e_FSParsePageNormal, NULL, false, &progressive);
java
import static com.foxit.sdk.pdf.PDFDoc.*;
import static com.foxit.sdk.pdf.PDFPage.*;
import static com.foxit.sdk.common.Constants.e_ErrSuccess;
import static com.foxit.sdk.pdf.PDFPage.e_ParsePageNormal;
...

PDFDoc doc = new PDFDoc("sample.pdf");
int error_code = doc.load(null);
if (error_code != e_ErrSuccess)
return;

// Get the first page of the document.
PDFPage page = doc.getPage(0);
// Parse page.
page.startParse(e_ParsePageNormal, null, false);
python
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    # replace with the python2 lib path
    site.addsitedir('../../../')  
    from FoxitPDFSDKPython2 import *
else:
    from FoxitPDFSDKPython3 import *

...
doc = PDFDoc("Sample.pdf")
error_code = doc.Load("")
if error_code!= e_ErrSuccess: 
    return 0
doc.SaveAs("new_Sample.pdf", PDFDoc.e_SaveFlagNoOriginal)
objective-c
#include "FSPDFObjC.h"
...

NSString* pdfpath = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"pdf"];
FSPDFDoc* doc = [[FSPDFDoc alloc] initWithPath:pdfpath];
FSErrorCode errorCode = [doc load:nil];
if (errorCode != FSErrSuccess) {
    return -1;
}

// Get the first page of the document.
FSPDFPage* page = [doc getPage:0];
// Parse page.
[page startParse:FSPDFPageParsePageNormal pause:nil is_reparse:NO];
javascript
const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");

...
let doc = new FSDK.PDFDoc("Sample.pdf");
let error_code = doc.Load("");
if (error_code != FSDK.e_ErrSuccess) {
    return 1;
}
let page = doc.GetPage(0);
page.StartParse(FSDK.PDFPage.e_ParsePageNormal, null, false);
csharp
using foxit.pdf;
using foxit.common;
...

PDFDoc doc = new PDFDoc("Sample.pdf");
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...
// Get the first page of the document.
PDFPage page = doc.GetPage(0);
// Parse page.
page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.e_ParsePageNormal, null, false);
...

将 PDF 文档另存为一个新的文档

c++
#include "include/pdf/fs_pdfdoc.h"
#include "include/pdf/fs_pdfpage.h"

using namespace foxit;
using namespace common;
using namespace pdf;
...

PDFDoc doc("Sample.pdf");
ErrorCode error_code = doc.Load();
if (error_code!= foxit::e_ErrSuccess) return 0;
doc.SaveAs("new_Sample.pdf", PDFDoc::e_SaveFlagNoOriginal);
c
#include "include/fs_basictypes_c.h"
#include "include/fs_pdfdoc_c.h"
#include "include/fs_pdfpage_c.h"
...

FS_PDFDOC_HANDLE doc;
FSDK_PDFDoc_Create0("Sample.pdf", &doc);
FSErrorCode error_code = FSDK_PDFDoc_Load(doc, NULL);
if (error_code!= e_FSErrSuccess) return 0;
FSDK_PDFDoc_SaveAs(doc, "new_Sample.pdf", e_FSSaveFlagNoOriginal);
java
import static com.foxit.sdk.pdf.PDFDoc.*;
import static com.foxit.sdk.pdf.PDFPage.*;
import static com.foxit.sdk.common.Constants.e_ErrSuccess;
import static com.foxit.sdk.pdf.PDFDoc.e_SaveFlagNoOriginal;
...

PDFDoc doc = new PDFDoc("sample.pdf");
int error_code = doc.load(null);
if (error_code != e_ErrSuccess)
return;
doc.saveAs("new_Sample.pdf", e_SaveFlagNoOriginal);
python
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    # replace with the python2 lib path
    site.addsitedir('../../../')  
    from FoxitPDFSDKPython2 import *
else:
    from FoxitPDFSDKPython3 import *

...
doc = PDFDoc("Sample.pdf")
error_code = doc.Load("")
if error_code!= e_ErrSuccess: 
    return 0
doc.SaveAs("new_Sample.pdf", PDFDoc.e_SaveFlagNoOriginal)
objective-c
#include "FSPDFObjC.h"
...

NSString* pdfpath = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"pdf"];
FSPDFDoc* doc = [[FSPDFDoc alloc] initWithPath:pdfpath];
FSErrorCode errorCode = [doc load:nil];
if (errorCode != FSErrSuccess) {
    return -1;
}

[doc saveAs:output_file save_flags:FSPDFDocSaveFlagNoOriginal];
javascript
const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");

...
let doc = new FSDK.PDFDoc("Sample.pdf");
let error_code = doc.Load("");
if (error_code != FSDK.e_ErrSuccess) {
    return 1;
}
doc.SaveAs("new_Sample.pdf", FSDK.PDFDoc.e_SaveFlagNoOriginal);
csharp
using foxit.pdf;
using foxit.common;
...

PDFDoc doc = new PDFDoc("Sample.pdf");
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...
// Do operations for the PDF document.
...
// Save the changes for the PDF document.
string newPdf = "the output path for the saved PDF";
doc.SaveAs(newPdf, (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);

通过回调将 PDF 文档保存到内存缓冲区

c++
#include "include/pdf/fs_pdfdoc.h"
#include "include/pdf/fs_pdfpage.h"

using namespace foxit;
using namespace common;
using namespace pdf;
...

// FileWriter for saving file to memory buffer.
class  FileWriter:public common::file::WriterCallback
{
public:
 FileWriter() {}

 ~FileWriter()  {}

 FILESIZE GetSize() {
  return  binary_buffer_.GetSize();
 }

 FX_BOOL Flush() {
  return  TRUE;
 }

 FX_BOOL WriteBlock(const void* buffer,FILESIZE offset,size_t size) {
  return  binary_buffer_.InsertBlock(offset,buffer,size);
 }

 FX_BOOL  ReadBlock(void* buffer,FILESIZE offset,size_t size)    {
  FX_LPBYTE byte_buffer = binary_buffer_.GetBuffer();
  memcpy(buffer, byte_buffer + offset, size);
 }

 void Release() {
 }

 CFX_BinaryBuf GetBuffer() {
  return binary_buffer_;
 }
private:
 CFX_BinaryBuf binary_buffer_;
};
...

FileWriter* filewriter = new FileWriter();

// Assuming PDFDoc doc has been loaded.
...

doc.StartSaveAs(filewriter, PDFDoc::e_SaveFlagNoOriginal);
...
c
#include "include/fs_basictypes_c.h"
#include "include/fs_pdfdoc_c.h"
#include "include/fs_pdfpage_c.h"
...

// FileWriter for saving file to memory buffer.
...

CFX_BinaryBuf *binary_buffer_;

FS_INT64 gGetSizeFileWriter(void* user_data) {
  return binary_buffer_->GetSize();
}

FS_BOOL gFlushFileWriter(void* user_data) {
  return TRUE;
}

FS_BOOL gWriteBlockFileWriter(void* user_data, const void* buffer, FS_INT64 offset, size_t size) {
  return binary_buffer_->InsertBlock(offset,buffer,size);}

static void gReleaseFileWriter(void* user_data) {
}


// Assuming FS_PDFDOC_HANDLE doc has been loaded.
...
FSWriterCallback* filewritercallback = (FSWriterCallback*)malloc(sizeof(FSWriterCallback));
filewritercallback->user_data = filewritercallback;
filewritercallback->Flush = gFlushFileWriter;
filewritercallback->GetSize = gGetSizeFileWriter;
filewritercallback->WriteBlock = gWriteBlockFileWriter;
filewritercallback->Release = gReleaseFileWriter;

FS_PROGRESSIVE_HANDLE return_StartSaveAs;
FSDK_PDFDoc_StartSaveAs0(doc, filewriter, e_FSSaveFlagNoOriginal, NULL , &return_StartSaveAs);
...
java
import static com.foxit.sdk.pdf.PDFDoc.*;
import static com.foxit.sdk.common.Constants.e_ErrSuccess;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
...

class FileWriter extends FileWriterCallback {
    private ByteArrayOutputStream buf = new ByteArrayOutputStream();
 
    @Override
    public long getSize() {
        return buf.size();
    }
 
    @Override
    public boolean writeBlock(byte[] buffer, long offset, long size) {
        buf.write(buffer, (int)0, (int)size);
        return true;
    }
     
    @Override
    public void release() {
    }
     
    @Override
    public boolean flush() {
        return true;
    }
}
  
...
FileWriter filewriter = new FileWriter();

// Assuming PDFDoc doc has been loaded.
...

doc.startSaveAs(filewriter, e_SaveFlagNoOriginal,null);
...
python
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    # replace with the python2 lib path
    site.addsitedir(‘../../../’)
    from FoxitPDFSDKPython2 import *
else:
    from FoxitPDFSDKPython3 import *

class FileWriter(FileWriterCallback):
    def __init__(self, *args):
        if _PYTHON2_:
            super(FileWriter, self).__init__()
        else:
            super().__init__()
        self.binary_buffer_ = bytearray(b'')

    def __del__(self):
        self.__disown__()

    def Release(self, *args):
        pass

    def GetSize(self, *args):        
        file_size = len(self.binary_buffer_)
        return file_size

    def ReadBlock(self, *args):
        size = 0
        if len(args) == 2:
            offset = args[0]
            size = args[1]
            buffer = bytes(self.binary_buffer_[offset:offset+size])
            return True, buffer
        else:
            return False, None

    def Flush(self, *args):
        return True

    def WriteBlock(self, *args):
        self.binary_buffer_[args[0][1]:0] = args[0][0]
        return True

file_writer = FileWriter()
# Assuming PDFDoc doc has been loaded.
doc.StartSaveAs(file_writer, PDFDoc.e_SaveFlagNoOriginal)
...
objective-c
#include "FSPDFObjC.h"
...

@interface FSFileWriterCallbackImpl : NSObject<FSFileWriterCallback>
@property (nonatomic) NSMutableData* mutableData;
@end
 
@implementation FSFileWriterCallbackImpl
- (instancetype)init
    {
            self = [super init];
            if (self) {
                    _mutableData = [[NSMutableData alloc] init];
                }
            return self;
        }
-(unsigned long long)getSize {
        if (!self.mutableData) return NO;
         
        return self.mutableData.length;
}
     
-(BOOL)writeBlock:(NSData*)data offset:(unsigned long long)offset {
        if (!self.mutableData) return NO;
     
        [self.mutableData appendData:data];
        return YES;
}
     
-(BOOL)flush {
        return YES;
}
@end
 
...
FSFileWriterCallbackImpl* filewriter = [[FSFileWriterCallbackImpl alloc] init];

// Assuming FSPDFDoc doc has been loaded.
...

[doc startSaveAsWithWriterCallback:filewriter save_flags:FSPDFDocSaveFlagNoOriginal pause:nil];
...
javascript
const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");
const fs = require('fs');
const os = require('os');
const path = require('path');
const util = require('util');


class FileWriter {
    constructor() {
        this.m_fileFP = null;
        this.file_path_ = "";
    }

    LoadFile(file_path) {
        try {
            this.file_path_ = file_path;
            this.m_fileFP = fs.openSync(file_path, 'w');
            if (!this.m_fileFP) {
                return false;
            }
            return true;
        } catch (err) {
            console.error(err);
            return false;
        }
    }

    GetSize() {
        try {
            let stats = fs.statSync(this.file_path_);
            return stats.size;
        } catch (err) {
            console.error(err);
            return 0;
        }
    }

    Flush() {
        return true;
    }

    WriteBlock(buffer, offset, size) {
        try {
            const write_size = fs.writeSync(this.m_fileFP, buffer, 0, size, offset);
            if (write_size == size) {
                return true;
            } else {
                return false;
            }
        } catch (err) {
            console.error(err);
            return false;
        }
    }

    Release() {
        try {
            fs.closeSync(this.m_fileFP);
            this.m_fileFP = null;
        } catch (err) {
            console.error(err);

        }
    }
}

let filewrite = new FileWriter();
let write_callback = new FSDK.FileWriterCallback(filewrite);
doc.SaveAs(write_callback, FSDK.PDFDoc.e_SaveFlagNoOriginal);
...
csharp
using foxit.pdf;
using foxit.common;
using foxit.common.fxcrt;
using System.IO;
using System.Runtime.InteropServices;
...

class FileWriter : FileWriterCallback
{
     private MemoryStream memoryfilestream = new MemoryStream();
     public FileWriter()
     {
     }

     public override long GetSize()
     {
         return this.memoryfilestream.Length;
     }

     public override bool WriteBlock(IntPtr pData, long offset, uint size)
     {
         byte[] ys = new byte[size];
         Marshal.Copy(pData, ys, 0, (int)size);
         memoryfilestream.Write(ys, 0, (int)size);
         return true;
     }

     public override bool Flush()
     {
         return true;
     }

     public override void Release()
     {
     }
}
...

FileWriter fileWriter = new FileWriter();

// Assuming PDFDoc doc has been loaded.
...

doc.StartSaveAs(fileWriter, (int) PDFDoc.SaveFlags.e_SaveFlagNoOriginal, null);
...