Compare commits

...

56 Commits

Author SHA1 Message Date
8550bdeed6 Generate all projects if ommited 2024-10-24 18:05:56 +04:00
5aae57aad8 Log generated project files 2024-10-24 17:43:04 +04:00
1d4f825ea6 Add note to change builder directory for cpp & cs 2024-10-23 13:53:30 +04:00
0527472fef Use space indentation for consistency 2024-10-22 22:00:45 +04:00
c911733bd7 Fix crash on mac 2024-10-22 21:51:21 +04:00
46f254c85d Fix incorrect convertation to string 2024-10-22 20:43:03 +04:00
a6a7d919e6 Add README.md 2024-10-21 16:47:52 +04:00
755d6cd970 Add some Java samples 2024-10-21 15:04:22 +04:00
604dc14d23 Add some python samples 2024-10-18 18:00:54 +04:00
2263d7bf80 Fix Makefile for mac 2024-10-18 14:04:30 +04:00
ef415aad3f Fixes for mac 2024-10-17 18:55:42 +04:00
6744c172f4 Remove C++ compile warnings 2024-10-17 17:43:53 +04:00
6ea3a9551e Add generation of Makefile 2024-10-17 17:35:51 +04:00
f48ab0351c Update help message with C# projects 2024-10-17 15:28:29 +04:00
632ddf9805 Remove asterisks due to portability 2024-10-17 15:22:27 +04:00
2c61e84e94 Fix unresolved symbols on linux 2024-10-17 14:38:21 +04:00
375b37e9aa Add include paths for utils 2024-10-16 19:07:29 +04:00
bb3e2e3bc2 Fix issue with relative paths to resources 2024-10-16 18:20:04 +04:00
1a5b8b4bbd Add generation of Qt C++ projects 2024-10-16 18:17:40 +04:00
901c44b486 Add generation of VS .NET projects 2024-10-15 19:00:29 +04:00
88eadd9955 Add remaining C++ samples 2024-10-15 16:04:23 +04:00
b5f88cebaf Fix C++ projects for old VS versions
+ Add spreadsheet test
2024-10-15 14:52:14 +04:00
e0e7e31568 Add generation of VS C++ projects 2024-10-14 20:18:57 +04:00
00344df9ad Fix for -D with brackets 2024-10-09 11:27:54 +03:00
cfb060e142 Fix build 2024-10-09 11:05:28 +03:00
0565e6164b Add data for hard update hunspell module 2024-10-09 10:47:24 +03:00
306cc3f985 For bug 70578 2024-10-08 23:31:46 +03:00
2739dd3abd Fix bug 69154 2024-10-08 22:54:19 +03:00
70e6df5aae fix bug #70440 2024-10-08 22:00:45 +03:00
96030aa322 Set timelimits of dictionaries tester bigger 2024-10-08 15:18:40 +03:00
fee801eeeb Merge pull request 'Add custom timelimits logic in dictionariestester' (#59) from fix/dictionariestester into release/v8.2.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/59
2024-10-08 11:55:37 +00:00
750273b526 Change timelimits 2024-10-08 14:51:48 +03:00
cfdb541c28 Add custom timelimits logic in dictionariestester 2024-10-08 14:36:30 +03:00
11121961d9 Fix typo 2024-10-08 08:47:12 +00:00
45828709ee Merge pull request 'Fix bug #70515' (#57) from fix/bug70515 into release/v8.2.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/57
2024-10-08 08:15:23 +00:00
40916e5ccc Merge pull request 'Fix bug 60796' (#56) from fix/bug60796 into release/v8.2.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/56
2024-10-08 08:07:18 +00:00
319610c58d Fix bug 60796 2024-10-08 10:22:32 +03:00
1837a2737e Fix RefTo id 2024-10-07 15:17:03 +00:00
686fc60860 For bug 61203 2024-10-07 15:17:03 +00:00
51216f27f4 Fix bug 70466 2024-10-07 17:47:12 +03:00
2eb33ddd22 Merge pull request 'Fix bug #70484' (#30) from fix/bug70484 into release/v8.2.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/30
2024-10-07 14:05:10 +00:00
58c80b052b Merge pull request 'Fix bug #70492' (#34) from fix/bug70492 into release/v8.2.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/34
2024-10-07 14:04:42 +00:00
5eee408eeb Merge pull request 'Fix bug #70617' (#54) from fix/bug70617 into release/v8.2.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/54
2024-10-07 14:04:20 +00:00
b6ae1f272c Fix bug #70617 2024-10-07 15:41:28 +05:00
045f23d921 Fix bug 68091 2024-10-07 02:46:38 +03:00
d06b52988c Fix bug 70352 2024-10-06 18:56:06 +00:00
4717b47388 Fix bug in metafile conversion 2024-10-06 17:11:32 +00:00
31ce9f6a18 Fix bug #66337 2024-10-06 17:11:32 +00:00
e44c9fa4c9 Fix bug #31062 2024-10-06 17:11:32 +00:00
3c59ba7a13 fixed a bug with the location of the embedded metafile 2024-10-06 17:11:32 +00:00
42e84249e8 For bug #68708 2024-10-06 17:11:32 +00:00
e2dbde8722 fix bug #70163 2024-10-06 11:43:33 +03:00
36c67d79d5 fix bug #70717 2024-10-06 11:17:16 +03:00
a9752208f6 Fix bug #70515 2024-10-03 15:43:45 +05:00
5a6386e08b Fix bug #70492 2024-09-27 20:07:14 +05:00
9b5f762420 Fix bug #70484 2024-09-26 17:35:25 +05:00
70 changed files with 3640 additions and 136 deletions

View File

@ -2,3 +2,4 @@ emsdk/
hunspell/
deploy/
o
hunspell.data

View File

@ -14,6 +14,12 @@ def get_hunspell(stable_commit):
base.replaceInFile("./src/hunspell/csutil.cxx", "void free_utf_tbl() {", "void free_utf_tbl() { \n return;\n")
# bug fix, we need to keep this utf table
# free_utf_tbl doesnt delete anything so we can destroy hunspell object
# replace & add defines to easy control of time limits (CUSTOM_LIMIT)
default_tl_defines = "#define TIMELIMIT_GLOBAL (CLOCKS_PER_SEC / 4)\n#define TIMELIMIT_SUGGESTION (CLOCKS_PER_SEC / 10)\n#define TIMELIMIT (CLOCKS_PER_SEC / 20)\n"
custom_tl_defines_tl = "#define TIMELIMIT_GLOBAL CUSTOM_TIMELIMIT_GLOBAL\n#define TIMELIMIT_SUGGESTION CUSTOM_TIMELIMIT_SUGGESTION\n#define TIMELIMIT CUSTOM_TIMELIMIT\n"
tl_defines = "#ifndef CUSTOM_TIMELIMITS\n" + default_tl_defines + "#else\n" + custom_tl_defines_tl + "#endif\n"
base.replaceInFile("./src/hunspell/atypes.hxx", default_tl_defines, tl_defines)
os.chdir("../")

View File

@ -14,12 +14,32 @@ DEFINES += KERNEL_USE_DYNAMIC_LIBRARY
TEMPLATE = app
CONFIG += hunspell_build_static
CORE_ROOT_DIR = $$PWD/../../../..
PWD_ROOT_DIR = $$PWD
include($$CORE_ROOT_DIR/Common/base.pri)
include($$CORE_ROOT_DIR/Common/3dParty/icu/icu.pri)
include($$CORE_ROOT_DIR/Common/3dParty/hunspell/qt/hunspell.pri)
ADD_DEPENDENCY(UnicodeConverter kernel hunspell)
# custom time limits of hunspell in clocks (if before.py was executed)
# when increasing the limit for each case, it is important to consider that the total time will
# also increase, so it is good to increase the global limit. this works the same for the candidate limit with suggest limit
DEFINES += CUSTOM_TIMELIMITS
escape_bracket=
!core_windows:escape_bracket=\\
# total time limit per word for all cases. (default is CLOCKS_PER_SEC/4)
DEFINES += "CUSTOM_TIMELIMIT_GLOBAL=$${escape_bracket}(20*CLOCKS_PER_SEC$${escape_bracket})"
# total time limit per "1 case" - forgotten char, double char, moved char and so on for all candidates. (default is CLOCKS_PER_SEC/10)
DEFINES += "CUSTOM_TIMELIMIT_SUGGESTION=$${escape_bracket}(5*CLOCKS_PER_SEC$${escape_bracket})"
# time limit per candidate (default is CLOCKS_PER_SEC/20)
DEFINES += "CUSTOM_TIMELIMIT=$${escape_bracket}(CLOCKS_PER_SEC$${escape_bracket}\)"
ADD_DEPENDENCY(UnicodeConverter kernel)
core_windows:LIBS += -lgdi32 -ladvapi32 -luser32 -lshell32

View File

@ -648,7 +648,7 @@ namespace NSStringUtils
}
void CStringBuilder::AddInt(int val)
{
AddSize(10);
AddSize(11);
AddIntNoCheck(val);
}
void CStringBuilder::AddUInt(unsigned int val)
@ -683,6 +683,9 @@ namespace NSStringUtils
if (val < 0)
{
val = -val;
if (val < 0)
val = 2147483647;
*m_pDataCur++ = (wchar_t)'-';
++m_lSizeCur;
}

View File

@ -445,7 +445,7 @@ namespace NSDoctRenderer
strError = L"code=\"save\"";
bIsBreak = true;
}
else
else if (!js_result2->isNull())
{
JSSmart<CJSTypedArray> typedArray = js_result2->toTypedArray();
NSJSBase::CJSDataBuffer oBuffer = typedArray->getData();

View File

@ -0,0 +1,9 @@
!*.vcxproj.user
!Makefile
out/
*.docx
*.pptx
*.xlsx
*.class

View File

@ -0,0 +1,156 @@
- [Document Builder samples](#document-builder-samples)
- [About](#about)
- [Project generator: configure.py](#project-generator-configurepy)
- [Running C++ samples](#running-c-samples)
- [Visual Studio](#visual-studio)
- [Qt](#qt)
- [Makefile](#makefile)
- [Running C# samples](#running-c-samples-1)
- [Visual Studio](#visual-studio-1)
- [Running Python samples](#running-python-samples)
- [Running Java samples](#running-java-samples)
# Document Builder samples
## About
Here you can find some code samples for Document Builder library in different programming languages:
1. [C++](#running-c-samples)
2. [C# (.NET)](#running-c-samples-1)
3. [Python](#running-python-samples)
4. [Java](#running-java-samples)
## Project generator: configure.py
For running C++ and C# code samples use python script `configure/configure.py` which is able to generate:
+ Visual Studio project files
+ Qt project file
+ Makefile
To use `configure.py` you need to specify following options:
1. Which project files to generate: `--vs`, `--qt` or `--make`. Several options are available at the same time, but some of them are not supported on all platforms. In case you provide none of these options, all available projects will be generated.
2. Test samples with `--test TEST`. Some available options:
- `--test all` generate projects for both C++ and C#.
- `--test cpp` generate projects only for C++ samples
- `--test cs` generate projects only for C# samples.
- `--test cpp/creating_basic_form` generate only project for the specified sample.
Several test options are available at the same time. To see all available `TEST` options call `configure.py -l`.
3. Directory to the Document Builder with `--dir DIR`. If Document Builder is not installed in default path you have to provide path to it.
Generated files will be located in the `out` directory inside of the corresponding test folders.
## Running C++ samples
If Document Builder is not installed in `C:/Program Files/ONLYOFFICE/DocumentBuilder`, for every C++ sample you should change the `workDir` variable at the beginning of *main.cpp* to actual location of Document Builder directory.
### Visual Studio
> **NOTE:** Only available on Windows
1. Use `configure.py` to generate VS project files. For example:
```shell
python configure.py --vs --test cpp/creating_basic_form --test cpp/creating_advanced_form
```
2. Open `.sln` file in Visual Studio. It will prompt you to retarget Windows SDK and VS toolset to your installed version click "OK".
3. The solution is ready to be built and run. Documents will be created in the project files directory.
### Qt
1. Use `configure.py` to generate Qt project files. For example:
```shell
python configure.py --qt --test cpp
```
2. Open `.pro` file in Qt Creator.
3. The project is ready to be built and run. Documents will be created in the `build` directory.
### Makefile
> **NOTE:** Only available on Linux and Mac OS.
1. Use `configure.py` to generate Makefile. For example:
```shell
python configure.py --make --test cpp/filling_spreadsheet
```
2. Go to the directory with generated Makefile:
```shell
cd ../out/cpp/filling_spreadsheet
```
3. Call
```shell
make
```
`make` will build and run the executable. Documents will be created in the same directory as Makefile is.
## Running C# samples
> **NOTE:** Only available on Windows with Visual Studio and .NET SDK installed
If Document Builder is not installed in `C:/Program Files/ONLYOFFICE/DocumentBuilder`, for every C# sample you should change the `workDirectory` variable at the beginning of `Main` function to actual location of Document Builder directory.
### Visual Studio
1. Use `configure.py` to generate VS project files. For example:
```shell
python configure.py --vs --test cs
```
2. Open `.sln` file in Visual Studio. Depending on your installed .NET SDK version you may need to set different target framework by setting it in Visual Studio project properties or editing it directly in the `.csproj` file.
3. The solution is ready to be built and run. Documents will be created in the project files directory.
## Running Python samples
1. Go to test directory:
```shell
cd python/creating_basic_form
```
2. If it is needed, edit path to builder directory at the beginning of the python script:
```py
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
```
3. Run the script
```shell
python main.py
```
Documents will be created in the test directory.
## Running Java samples
> **NOTE:** JDK 8 or newer is required
1. Go to test directory:
```shell
cd java/creating_presentation
```
2. Compile the `Program.java` providing the path to ***docbuilder.jar***, located in the Document Builder directory:
```shell
javac -cp "C:\Program Files\ONLYOFFICE\DocumentBuilder\docbuilder.jar" Program.java
```
3. `.class` file should appear in the directory. Run the program:
```shell
java -cp "C:\Program Files\ONLYOFFICE\DocumentBuilder\docbuilder.jar;." Program
```
Note, that on UNIX systems the path separator is `:` instead of `;`. Thus, on Linux or Mac OS it should be:
```shell
java -cp "/opt/onlyoffice/documentbuilder/docbuilder.jar:." Program
```
3. Documents will be created in the test directory.

View File

@ -0,0 +1,293 @@
import os
import argparse
import platform
import uuid
langs = ['cpp', 'cs']
os_name = platform.system().lower()
def mkdir(dir):
if not os.path.exists(dir):
os.mkdir(dir)
def log(level, message):
print('configure.py: ' + level + ': ' + message)
def getDefaultBuilderDir():
dir = ''
if os_name == 'windows':
dir = 'C:\\Program Files\\ONLYOFFICE\\DocumentBuilder'
elif os_name == 'linux':
dir = '/opt/onlyoffice/documentbuilder'
return dir
def getAllTests():
tests = {}
for lang in langs:
tests[lang] = []
test_dirs = os.listdir(lang)
for test_dir in test_dirs:
if not os.path.isdir(lang + '/' + test_dir):
continue
tests[lang].append(lang + '/' + test_dir)
return tests
def printAvailableTests():
all_tests = getAllTests()
print('all')
for lang in langs:
print('-----')
print(lang)
tests = all_tests[lang]
for test in tests:
print(test)
class PrintTestsList(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
printAvailableTests()
exit()
def getSelectedTests(tests):
all_tests = getAllTests()
# make set of all available tests
tests_set = {'all'}
for lang in langs:
tests_set.add(lang)
tests_set.update(all_tests[lang])
# make dict with set of selected tests
tests_selected = {lang: set() for lang in langs}
# filter tests through only available ones
for test in tests:
if not test in tests_set:
log('warning', 'wrong test "' + test + '". Call script with --list (or -l) to see all available tests')
continue
if test == 'all':
for lang in langs:
tests_selected[lang].update(all_tests[lang])
elif not '/' in test:
lang = test
tests_selected[lang].update(all_tests[lang])
else:
lang = test.split('/')[0]
tests_selected[lang].add(test)
# delete empty tests
for lang in langs:
if not tests_selected[lang]:
del tests_selected[lang]
return tests_selected
def replacePlaceholders(template_file, output_file, replacements):
content = ''
# open and read template file
with open(template_file, 'r') as file:
content = file.read()
# replace all placeholders with corresponding values
for placeholder, replacement in replacements.items():
content = content.replace(placeholder, replacement)
# write result to output file
with open(output_file, 'w') as file:
file.write(content)
def genVSProjectsCPP(tests, builder_dir):
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/' + test_name + '.vcxproj'):
log('info', 'VS C++ project for sample "' + test + '" already exists. Skipping.')
continue
else:
log('info', 'generating VS C++ project for sample "' + test + '"...')
# .vcxproj
project_guid = str(uuid.uuid4())
replacements = {
'[PROJECT_GUID]': project_guid,
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
'[ROOT_DIR]': os.getcwd()
}
replacePlaceholders('configure/project_templates/cpp/template.vcxproj', test_dir + '/' + test_name + '.vcxproj', replacements)
# .sln
replacements = {
'[SOLUTION_GUID]': str(uuid.uuid4()).upper(),
'[TEST_NAME]': test_name,
'[PROJECT_GUID]': project_guid.upper(),
'[EXT_GLOBALS_GUID]': str(uuid.uuid4()).upper()
}
replacePlaceholders('configure/project_templates/cpp/template.sln', test_dir + '/' + test_name + '.sln', replacements)
# .vcxproj.filters
replacements = {
'[GUID_SOURCE_FILES]': str(uuid.uuid4()).upper(),
'[GUID_HEADER_FILES]': str(uuid.uuid4()).upper(),
'[GUID_RESOURCE_FILES]': str(uuid.uuid4()).upper(),
'[TEST_NAME]': test_name
}
replacePlaceholders('configure/project_templates/cpp/template.vcxproj.filters', test_dir + '/' + test_name + '.vcxproj.filters', replacements)
# .vcxproj.user
replacements = {
'[BUILDER_DIR]': builder_dir
}
replacePlaceholders('configure/project_templates/cpp/template.vcxproj.user', test_dir + '/' + test_name + '.vcxproj.user', replacements)
def genVSProjectsCS(tests, builder_dir):
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/' + test_name + '.csproj'):
log('info', 'VS C# project for sample "' + test + '" already exists. Skipping.')
continue
else:
log('info', 'generating VS C# project for sample "' + test + '"...')
# .csproj
project_guid = str(uuid.uuid4())
replacements = {
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
}
replacePlaceholders('configure/project_templates/cs/template.csproj', test_dir + '/' + test_name + '.csproj', replacements)
# .sln
replacements = {
'[SOLUTION_GUID]': str(uuid.uuid4()).upper(),
'[TEST_NAME]': test_name,
'[PROJECT_GUID]': project_guid.upper(),
'[EXT_GLOBALS_GUID]': str(uuid.uuid4()).upper()
}
replacePlaceholders('configure/project_templates/cs/template.sln', test_dir + '/' + test_name + '.sln', replacements)
def genVSProjects(tests_selected, builder_dir):
if os_name != 'windows':
log('warning', 'generating Visual Studio projects is only available on Windows')
return
builder_dir = builder_dir.replace('/', '\\')
for lang, tests in tests_selected.items():
mkdir('out/' + lang)
if lang == 'cpp':
genVSProjectsCPP(tests, builder_dir)
elif lang == 'cs':
genVSProjectsCS(tests, builder_dir)
def genQtProjects(tests_selected, builder_dir):
# only for C++ projects
if 'cpp' not in tests_selected:
return
root_dir = os.getcwd()
if os_name == 'windows':
builder_dir = builder_dir.replace('\\', '/')
root_dir = root_dir.replace('\\', '/')
tests = tests_selected['cpp']
mkdir('out/cpp')
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/' + test_name + '.pro'):
log('info', 'Qt project for sample "' + test + '" already exists. Skipping.')
continue
else:
log('info', 'generating Qt C++ project for sample "' + test + '"...')
# .pro
replacements = {
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
'[ROOT_DIR]': root_dir
}
replacePlaceholders('configure/project_templates/cpp/template.pro', test_dir + '/' + test_name + '.pro', replacements)
def genMakefile(tests_selected, builder_dir):
# only for C++ projects
if 'cpp' not in tests_selected:
return
if os_name == 'windows':
log('warning', 'generating Makefile is not available on Windows')
return
# initialize variables
compiler = ''
lflags = ''
env_lib_path = ''
if os_name == 'linux':
compiler = 'g++'
lflags = '-Wl,--unresolved-symbols=ignore-in-shared-libs'
env_lib_path = 'LD_LIBRARY_PATH'
elif os_name == 'darwin':
compiler = 'clang++'
env_lib_path = 'DYLD_LIBRARY_PATH'
root_dir = os.getcwd()
tests = tests_selected['cpp']
mkdir('out/cpp')
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/Makefile'):
log('info', 'Makefile for sample "' + test + '" already exists. Skipping.')
else:
log('info', 'generating Makefile for C++ sample "' + test + '"...')
continue
# Makefile
replacements = {
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
'[ROOT_DIR]': root_dir,
'[COMPILER]': compiler,
'[LFLAGS]': lflags,
'[ENV_LIB_PATH]': env_lib_path
}
replacePlaceholders('configure/project_templates/cpp/Makefile', test_dir + '/Makefile', replacements)
if __name__ == '__main__':
# go to root dir
file_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(file_dir + '/..')
# initialize argument parser
parser = argparse.ArgumentParser(description='Generate project files for Document Builder samples')
parser.add_argument('--vs', action='store_true', help='create Visual Studio (.vcxproj and .csproj) project files')
parser.add_argument('--qt', action='store_true', help='create Qt (.pro) project files')
parser.add_argument('--make', action='store_true', help='create Makefile')
parser.add_argument('-t', '--test', dest='tests', action='append', help='specifies tests to generate project files', required=True)
parser.add_argument('-l', '--list', action=PrintTestsList, nargs=0, help='show list of available tests and exit')
builder_dir = getDefaultBuilderDir()
if builder_dir:
parser.add_argument('--dir', action='store', help='specifies Document Builder directory (default: ' + builder_dir + ')', default=builder_dir)
else:
parser.add_argument('--dir', action='store', help='specifies Document Builder directory', required=True)
args = parser.parse_args()
# validate arguments
if not os.path.exists(args.dir):
log('error', 'Document Builder directory doesn\'t exist: ' + args.dir)
exit(1)
if not (args.vs or args.qt or args.make):
if os_name == 'windows':
args.vs = True
args.qt = True
if os_name != 'windows':
args.make = True
# filter tests
tests_selected = getSelectedTests(args.tests)
# generate projects
mkdir('out')
# VS
if args.vs:
genVSProjects(tests_selected, args.dir)
elif 'cs' in tests_selected:
log('warning', 'generating C# projects only available ' + ('on Windows ' if os_name != 'windows' else '') + 'with --vs')
# Qt
if args.qt:
genQtProjects(tests_selected, args.dir)
# Makefile
if args.make:
genMakefile(tests_selected, args.dir)

View File

@ -0,0 +1,29 @@
CXX = [COMPILER]
CXXFLAGS = -std=gnu++11 -Wall -W -fPIC
INCPATH = -I[BUILDER_DIR]/include -I[ROOT_DIR]
LINK = [COMPILER]
LFLAGS = [LFLAGS]
LIBS = -L[BUILDER_DIR] -ldoctrenderer
BUILD_DIR = build
SRC = ../../../cpp/[TEST_NAME]/main.cpp
OBJ = $(BUILD_DIR)/main.o
TARGET = $(BUILD_DIR)/[TEST_NAME]
.PHONY: all run clean
all: $(TARGET) run
$(TARGET): $(OBJ)
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJ) $(LIBS)
$(OBJ): $(SRC)
@test -d $(BUILD_DIR) || mkdir -p $(BUILD_DIR)
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o $(OBJ) $(SRC)
run: $(TARGET)
[ENV_LIB_PATH]="[BUILDER_DIR]" ./$(TARGET)
clean:
@rm -rf $(BUILD_DIR)

View File

@ -0,0 +1,17 @@
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
TARGET = [TEST_NAME]
DESTDIR = $$PWD/build
BUILDER_DIR = "[BUILDER_DIR]"
ROOT_DIR = "[ROOT_DIR]"
INCLUDEPATH += $$BUILDER_DIR/include
INCLUDEPATH += $$ROOT_DIR
LIBS += -L$$BUILDER_DIR -ldoctrenderer
linux: QMAKE_LFLAGS += -Wl,--unresolved-symbols=ignore-in-shared-libs
SOURCES += ../../../cpp/[TEST_NAME]/main.cpp

View File

@ -0,0 +1,29 @@

Microsoft Visual Studio Solution File, Format Version 12.00
MinimumVisualStudioVersion = 10.0.40219.1
Project("{[SOLUTION_GUID]}") = "[TEST_NAME]", "[TEST_NAME].vcxproj", "{[PROJECT_GUID]}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{[PROJECT_GUID]}.Debug|x64.ActiveCfg = Debug|x64
{[PROJECT_GUID]}.Debug|x64.Build.0 = Debug|x64
{[PROJECT_GUID]}.Debug|x86.ActiveCfg = Debug|Win32
{[PROJECT_GUID]}.Debug|x86.Build.0 = Debug|Win32
{[PROJECT_GUID]}.Release|x64.ActiveCfg = Release|x64
{[PROJECT_GUID]}.Release|x64.Build.0 = Release|x64
{[PROJECT_GUID]}.Release|x86.ActiveCfg = Release|Win32
{[PROJECT_GUID]}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {[EXT_GLOBALS_GUID]}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{[PROJECT_GUID]}</ProjectGuid>
<RootNamespace>[TEST_NAME]</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>[BUILDER_DIR]\include;[ROOT_DIR];$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>[BUILDER_DIR]\include;[ROOT_DIR];$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>[BUILDER_DIR];%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>doctrenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>[BUILDER_DIR];%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>doctrenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\..\cpp\[TEST_NAME]\main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{[GUID_SOURCE_FILES]}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{[GUID_HEADER_FILES]}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{[GUID_RESOURCE_FILES]}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\cpp\[TEST_NAME]\main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LocalDebuggerEnvironment>PATH=[BUILDER_DIR];%PATH%
$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerEnvironment>PATH=[BUILDER_DIR];%PATH%
$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\cs\[TEST_NAME]\Program.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="[BUILDER_DIR]\docbuilder.net.dll" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,23 @@

Microsoft Visual Studio Solution File, Format Version 12.00
MinimumVisualStudioVersion = 10.0.40219.1
Project("{[SOLUTION_GUID]}") = "[TEST_NAME]", "[TEST_NAME].csproj", "{[PROJECT_GUID]}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{[PROJECT_GUID]}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{[PROJECT_GUID]}.Debug|Any CPU.Build.0 = Debug|Any CPU
{[PROJECT_GUID]}.Release|Any CPU.ActiveCfg = Release|Any CPU
{[PROJECT_GUID]}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {[EXT_GLOBALS_GUID]}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,90 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
#include "resources/utils/utils.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.xlsx";
// Helper functions
void CheckCell(CValue oWorksheet, wstring cell, int row, int col)
{
if (cell.find('#') != std::wstring::npos)
{
wstring commentMsg = L"Error: " + cell;
CValue errorCell = oWorksheet.Call("GetRangeByNumber", row, col);
errorCell.Call("AddComment", commentMsg.c_str());
}
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
// Open file and get context
wstring templatePath = NSUtils::GetResourcesDirectory() + L"/docs/spreadsheet_with_errors.xlsx";
oBuilder.OpenFile(templatePath.c_str(), L"");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Find and comment formula errors
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue oRange = oWorksheet.Call("GetUsedRange");
CValue data = oRange.Call("GetValue");
for (int row = 0; row < (int)data.GetLength(); row++)
{
for (int col = 0; col < (int)data[0].GetLength(); col++)
{
CheckCell(oWorksheet, data[row][col].ToString().c_str(), row, col);
}
}
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_SPREADSHEET_XLSX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,206 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.docx";
// Helper functions
string cValueToString(CValue value)
{
wchar_t* txt = value.ToString().c_str();
wstring ws(txt);
string str(ws.begin(), ws.end());
return str;
}
void setTableBorders(CValue oTable, int borderColor)
{
oTable.Call("SetTableBorderTop", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderBottom", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderLeft", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderRight", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideV", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideH", "single", 4, 0, borderColor, borderColor, borderColor);
}
CValue createFullWidthTable(CValue oApi, int rows, int cols, int borderColor)
{
CValue oTable = oApi.Call("CreateTable", cols, rows);
oTable.Call("SetWidth", "percent", 100);
setTableBorders(oTable, borderColor);
return oTable;
}
CValue getTableCellParagraph(CValue oTable, int row, int col)
{
return oTable.Call("GetCell", row, col).Call("GetContent").Call("GetElement", 0);
}
void addTextToParagraph(CValue oParagraph, std::string text, int fontSize, bool isBold)
{
oParagraph.Call("AddText", text.c_str());
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetBold", isBold);
}
void setPictureFormProperties(CValue oPictureForm, std::string key, std::string tip, bool required, std::string placeholder, std::string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, std::string imageUrl)
{
oPictureForm.Call("SetFormKey", key.c_str());
oPictureForm.Call("SetTipText", tip.c_str());
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder.c_str());
oPictureForm.Call("SetScaleFlag", scaleFlag.c_str());
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl.c_str());
}
void setTextFormProperties(CValue oTextForm, string key, string tip, bool required, string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key.c_str());
oTextForm.Call("SetTipText", tip.c_str());
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder.c_str());
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
void addTextFormToParagraph(CValue oParagraph, CValue oTextForm, int fontSize, string jc, bool hasBorder, int borderColor)
{
if (hasBorder)
{
oTextForm.Call("SetBorderColor", borderColor, borderColor, borderColor);
}
oParagraph.Call("AddElement", oTextForm);
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetJc", jc.c_str());
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create advanced form
CValue oDocument = oApi.Call("GetDocument");
CValue oTable = createFullWidthTable(oApi, 1, 2, 255);
CValue oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "PURCHASE ORDER", 36, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Serial # ", 25, true);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Serial", "Enter serial number", false, "Serial", true, 6, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oTable);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload company logo", false, "Photo", "tooBig", false, false, 0, 0, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Company Name", "Enter company name", false, "Company Name", true, 20, 1, false, false);
oParagraph = oApi.Call("CreateParagraph");
addTextFormToParagraph(oParagraph, oTextForm, 35, "left", false, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "Date: ", 25, true);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Date", "Date", false, "DD.MM.YYYY", true, 10, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "To:", 35, true);
oDocument.Call("Push", oParagraph);
oTable = createFullWidthTable(oApi, 1, 1, 200);
oParagraph = getTableCellParagraph(oTable, 0, 0);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Recipient", "Recipient", false, "Recipient", true, 25, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 32, "left", false, 255);
oDocument.Call("Push", oTable);
oTable = createFullWidthTable(oApi, 10, 2, 200);
oTable.Call("GetRow", 0).Call("SetBackgroundColor", 245, 245, 245, false);
CValue oCell = oTable.Call("GetCell", 0, 0);
oCell.Call("SetWidth", "percent", 30);
oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "Qty.", 30, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Description", 30, true);
for (int i = 1; i < 10; i++)
{
CValue oTempParagraph = getTableCellParagraph(oTable, i, 0);
CValue oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Qty" + std::to_string(i), "Qty" + std::to_string(i), false, " ", true, 9, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
oTempParagraph = getTableCellParagraph(oTable, i, 1);
oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Description" + std::to_string(i), "Description" + std::to_string(i), false, " ", true, 22, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
}
oDocument.Call("Push", oTable);
oDocument.Call("RemoveElement", 0);
oDocument.Call("RemoveElement", 1);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,108 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.docx";
// Helper functions
void setPictureFormProperties(CValue oPictureForm, std::string key, std::string tip, bool required, std::string placeholder, std::string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, std::string imageUrl)
{
oPictureForm.Call("SetFormKey", key.c_str());
oPictureForm.Call("SetTipText", tip.c_str());
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder.c_str());
oPictureForm.Call("SetScaleFlag", scaleFlag.c_str());
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl.c_str());
}
void setTextFormProperties(CValue oTextForm, std::string key, std::string tip, bool required, std::string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key.c_str());
oTextForm.Call("SetTipText", tip.c_str());
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder.c_str());
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create basic form
CValue oDocument = oApi.Call("GetDocument");
CValue oParagraph = oDocument.Call("GetElement", 0);
CValue oHeadingStyle = oDocument.Call("GetStyle", "Heading 3");
oParagraph.Call("AddText", "Employee pass card");
oParagraph.Call("SetStyle", oHeadingStyle);
oDocument.Call("Push", oParagraph);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload your photo", false, "Photo", "tooBig", true, false, 50, 50, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "First name", "Enter your first name", false, "First name", true, 13, 3, false, false);
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oTextForm);
oDocument.Call("Push", oParagraph);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,156 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include <vector>
#include "common.h"
#include "docbuilder.h"
#include "resources/utils/utils.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.pptx";
void addText(CValue oApi, int fontSize, string text, CValue oSlide, CValue oShape, CValue oParagraph, CValue oFill, string jc)
{
CValue oRun = oApi.Call("CreateRun");
CValue oTextPr = oRun.Call("GetTextPr");
oTextPr.Call("SetFontSize", fontSize);
oTextPr.Call("SetFill", oFill);
oTextPr.Call("SetFontFamily", "Tahoma");
oParagraph.Call("SetJc", jc.c_str());
oRun.Call("AddText", text.c_str());
oRun.Call("AddLineBreak");
oParagraph.Call("AddElement", oRun);
oSlide.Call("AddObject", oShape);
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
// Read chart data from xlsx
wstring templatePath = NSUtils::GetResourcesDirectory() + L"/docs/chart_data.xlsx";
oBuilder.OpenFile(templatePath.c_str(), L"");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue values = oWorksheet.Call("GetUsedRange").Call("GetValue");
int sizeX = values.GetLength();
int sizeY = values[0].GetLength();
vector<vector<wstring>> data(sizeX, vector<wstring>(sizeY));
for (int i = 0; i < sizeX; i++)
{
for (int j = 0; j < sizeY; j++)
{
data[i][j] = values[i][j].ToString().c_str();
}
}
oBuilder.CloseFile();
// Create chart presentation
oBuilder.CreateFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX);
oContext = oBuilder.GetContext();
oScope = oContext.CreateScope();
oGlobal = oContext.GetGlobal();
oApi = oGlobal["Api"];
CValue oPresentation = oApi.Call("GetPresentation");
CValue oSlide = oPresentation.Call("GetSlideByIndex", 0);
oSlide.Call("RemoveAllObjects");
CValue oRGBColor = oApi.Call("CreateRGBColor", 255, 244, 240);
CValue oFill = oApi.Call("CreateSolidFill", oRGBColor);
oSlide.Call("SetBackground", oFill);
CValue oStroke = oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill"));
CValue oShapeTitle = oApi.Call("CreateShape", "rect", 300 * 36000, 20 * 36000, oApi.Call("CreateNoFill"), oStroke);
CValue oShapeText = oApi.Call("CreateShape", "rect", 120 * 36000, 80 * 36000, oApi.Call("CreateNoFill"), oStroke);
oShapeTitle.Call("SetPosition", 20 * 36000, 20 * 36000);
oShapeText.Call("SetPosition", 210 * 36000, 50 * 36000);
CValue oParagraphTitle = oShapeTitle.Call("GetDocContent").Call("GetElement", 0);
CValue oParagraphText = oShapeText.Call("GetDocContent").Call("GetElement", 0);
oRGBColor = oApi.Call("CreateRGBColor", 115, 81, 68);
oFill = oApi.Call("CreateSolidFill", oRGBColor);
string titleContent = "Price Type Report";
string textContent = "This is an overview of price types. As we can see, May was the price peak, but even in June the price went down, the annual upward trend persists.";
addText(oApi, 80, titleContent, oSlide, oShapeTitle, oParagraphTitle, oFill, "center");
addText(oApi, 42, textContent, oSlide, oShapeText, oParagraphText, oFill, "left");
// Transform 2d array into cols names, rows names and data
CValue cols = oContext.CreateArray(sizeY - 1);
for (int col = 1; col < sizeY; col++)
{
cols[col - 1] = data[0][col].c_str();
}
CValue rows = oContext.CreateArray(sizeX - 1);
for (int row = 1; row < sizeX; row++)
{
rows[row - 1] = data[row][0].c_str();
}
CValue vals = oContext.CreateArray(sizeY - 1);
for (int row = 1; row < sizeY; row++)
{
CValue row_data = oContext.CreateArray(sizeX - 1);
for (int col = 1; col < sizeX; col++)
{
row_data[col - 1] = data[col][row].c_str();
}
vals[row - 1] = row_data;
}
// Pass CValue data to the CreateChart method
CValue oChart = oApi.Call("CreateChart", "lineStacked", vals, cols, rows);
oChart.Call("SetSize", 180 * 36000, 100 * 36000);
oChart.Call("SetPosition", 20 * 36000, 50 * 36000);
oChart.Call("ApplyChartStyle", 24);
oChart.Call("SetLegendFontSize", 12);
oChart.Call("SetLegendPos", "top");
oSlide.Call("AddObject", oChart);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,156 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <map>
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.pptx";
// Helper functions
CValue createImageSlide(CValue oApi, CValue oPresentation, string image_url)
{
CValue oSlide = oApi.Call("CreateSlide");
oPresentation.Call("AddSlide", oSlide);
CValue oFill = oApi.Call("CreateBlipFill", image_url.c_str(), "stretch");
oSlide.Call("SetBackground", oFill);
oSlide.Call("RemoveAllObjects");
return oSlide;
}
void addTextToSlideShape(CValue oApi, CValue oContent, string text, int fontSize, bool isBold, string js)
{
CValue oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("SetSpacingBefore", 0);
oParagraph.Call("SetSpacingAfter", 0);
oContent.Call("Push", oParagraph);
CValue oRun = oParagraph.Call("AddText", text.c_str());
oRun.Call("SetFill", oApi.Call("CreateSolidFill", oApi.Call("CreateRGBColor", 0xff, 0xff, 0xff)));
oRun.Call("SetFontSize", fontSize);
oRun.Call("SetFontFamily", "Georgia");
oRun.Call("SetBold", isBold);
oParagraph.Call("SetJc", js.c_str());
}
// Main function
int main()
{
map<string, string>slideImages;
slideImages["gun"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png";
slideImages["axe"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png";
slideImages["knight"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png";
slideImages["sky"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png";
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create presentation
CValue oPresentation = oApi.Call("GetPresentation");
oPresentation.Call("SetSizes", 9144000, 6858000);
CValue oSlide = createImageSlide(oApi, oPresentation, slideImages["gun"]);
oPresentation.Call("GetSlideByIndex", 0).Call("Delete");
CValue oShape = oApi.Call("CreateShape", "rect", 8056800, 3020400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 608400, 1267200);
CValue oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "How They", 160, true, "left");
addTextToSlideShape(oApi, oContent, "Throw Out", 132, false, "left");
addTextToSlideShape(oApi, oContent, "a Challenge", 132, false, "left");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["axe"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "American Indians ", 110, true, "right");
addTextToSlideShape(oApi, oContent, "(XVII century)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "put a tomahawk on the ground in the ", 84, false, "right");
addTextToSlideShape(oApi, oContent, "rival's camp", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["knight"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "European Knights", 110, true, "right");
addTextToSlideShape(oApi, oContent, " (XII-XVI centuries)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "threw a glove", 84, false, "right");
addTextToSlideShape(oApi, oContent, "in the rival's face", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["sky"]);
oShape = oApi.Call("CreateShape", "rect", 7887600, 3063600, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 630000, 1357200);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "OnlyOffice", 176, false, "center");
addTextToSlideShape(oApi, oContent, "stands for Peace", 132, false, "center");
oSlide.Call("AddObject", oShape);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,94 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <map>
#include <string>
#include "common.h"
#include "docbuilder.h"
#include "resources/utils/utils.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.docx";
// Main function
int main()
{
std::map<wstring, wstring> formData;
formData[L"Photo"] = L"https://api.onlyoffice.com/content/img/docbuilder/examples/blue_cloud.png";
formData[L"Serial"] = L"A1345";
formData[L"Company Name"] = L"Blue Cloud";
formData[L"Date"] = L"25.12.2023";
formData[L"Recipient"] = L"Space Corporation";
formData[L"Qty1"] = L"25";
formData[L"Description1"] = L"Frame";
formData[L"Qty2"] = L"2";
formData[L"Description2"] = L"Stack";
formData[L"Qty3"] = L"34";
formData[L"Description3"] = L"Shifter";
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
wstring templatePath = NSUtils::GetResourcesDirectory() + L"/docs/form.docx";
oBuilder.OpenFile(templatePath.c_str(), L"");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Fill form
CValue oDocument = oApi.Call("GetDocument");
CValue aForms = oDocument.Call("GetAllForms");
int formNum = 0;
while (formNum < (int)aForms.GetLength())
{
CValue form = aForms[formNum];
wstring type = aForms[formNum].Call("GetFormType").ToString().c_str();
wstring value = formData[aForms[formNum].Call("GetFormKey").ToString().c_str()];
if (type == L"textForm") form.Call("SetText", value.c_str());
if (type == L"pictureForm") form.Call("SetImage", value.c_str());
formNum++;
}
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,100 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.xlsx";
// Main function
int main()
{
string data[9][4] = {
{ "Id", "Product", "Price", "Available" },
{ "1001", "Item A", "12.2", "true" },
{ "1002", "Item B", "18.8", "true" },
{ "1003", "Item C", "70.1", "false" },
{ "1004", "Item D", "60.6", "true" },
{ "1005", "Item E", "32.6", "true" },
{ "1006", "Item F", "28.3", "false" },
{ "1007", "Item G", "11.1", "false" },
{ "1008", "Item H", "41.4", "true" }
};
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_SPREADSHEET_XLSX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Find and comment formula errors
CValue oWorksheet = oApi.Call("GetActiveSheet");
// Create CValue array from data
int rowsLen = sizeof data / sizeof data[0];
int colsLen = sizeof data[0] / sizeof(string);
CValue oArray = oContext.CreateArray(rowsLen);
for (int row = 0; row < rowsLen; row++)
{
CValue oArrayCol = oContext.CreateArray(colsLen);
for (int col = 0; col < colsLen; col++)
{
oArrayCol[col] = data[row][col].c_str();
}
oArray[row] = oArrayCol;
}
// First cell in the range (A1) is equal to (0,0)
CValue startCell = oWorksheet.Call("GetRangeByNumber", 0, 0);
// Last cell in the range is equal to array length -1
CValue endCell = oWorksheet.Call("GetRangeByNumber", oArray.GetLength() - 1, oArray[0].GetLength() - 1);
oWorksheet.Call("GetRange", startCell, endCell).Call("SetValue", oArray);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_SPREADSHEET_XLSX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,98 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CommentingErrors
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.xlsx";
string filePath = "../../../../../../resources/docs/spreadsheet_with_errors.xlsx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CommentErrors(workDirectory, resultPath, filePath);
}
public static void CommentErrors(string workDirectory, string resultPath, string filePath)
{
var doctype = (int)OfficeFileTypes.Spreadsheet.XLSX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.OpenFile(filePath, "xlsx");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Find and comment formula errors
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue oRange = oWorksheet.Call("GetUsedRange");
var data = oRange.Call("GetValue");
for (int row = 0; row < data.GetLength(); row++)
{
for (int col = 0; col < data[0].GetLength(); col++)
{
CheckCell(oWorksheet, data[row][col].ToString(), row, col);
}
}
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static void CheckCell(CValue oWorksheet, string cell, int row, int col)
{
if (cell.Contains("#"))
{
string comment = "Error" + cell;
CValue errorCell = oWorksheet.Call("GetRangeByNumber", row, col);
errorCell.Call("AddComment", comment);
}
}
}
}

View File

@ -0,0 +1,212 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CreatingAdvancedForm
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.docx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreateAdvancedForm(workDirectory, resultPath);
}
public static void CreateAdvancedForm(string workDirectory, string resultPath)
{
var doctype = (int)OfficeFileTypes.Document.DOCX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create advanced form
CValue oDocument = oApi.Call("GetDocument");
CValue oTable = createFullWidthTable(oApi, 1, 2, 255);
CValue oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "PURCHASE ORDER", 36, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Serial # ", 25, true);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Serial", "Enter serial number", false, "Serial", true, 6, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oTable);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload company logo", false, "Photo", "tooBig", false, false, 0, 0, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Company Name", "Enter company name", false, "Company Name", true, 20, 1, false, false);
oParagraph = oApi.Call("CreateParagraph");
addTextFormToParagraph(oParagraph, oTextForm, 35, "left", false, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "Date: ", 25, true);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Date", "Date", false, "DD.MM.YYYY", true, 10, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "To:", 35, true);
oDocument.Call("Push", oParagraph);
oTable = createFullWidthTable(oApi, 1, 1, 200);
oParagraph = getTableCellParagraph(oTable, 0, 0);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Recipient", "Recipient", false, "Recipient", true, 25, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 32, "left", false, 255);
oDocument.Call("Push", oTable);
oTable = createFullWidthTable(oApi, 10, 2, 200);
oTable.Call("GetRow", 0).Call("SetBackgroundColor", 245, 245, 245, false);
CValue oCell = oTable.Call("GetCell", 0, 0);
oCell.Call("SetWidth", "percent", 30);
oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "Qty.", 30, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Description", 30, true);
for (var i = 1; i < 10; i++)
{
CValue oTempParagraph = getTableCellParagraph(oTable, i, 0);
CValue oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Qty" + i, "Qty" + i, false, " ", true, 9, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
oTempParagraph = getTableCellParagraph(oTable, i, 1);
oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Description" + i, "Description" + i, false, " ", true, 22, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
}
oDocument.Call("Push", oTable);
oDocument.Call("RemoveElement", 0);
oDocument.Call("RemoveElement", 1);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static CValue createFullWidthTable(CValue oApi, int rows, int cols, int borderColor)
{
CValue oTable = oApi.Call("CreateTable", cols, rows);
oTable.Call("SetWidth", "percent", 100);
setTableBorders(oTable, borderColor);
return oTable;
}
public static void setTableBorders(CValue oTable, int borderColor)
{
oTable.Call("SetTableBorderTop", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderBottom", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderLeft", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderRight", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideV", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideH", "single", 4, 0, borderColor, borderColor, borderColor);
}
public static CValue getTableCellParagraph(CValue oTable, int row, int col)
{
return oTable.Call("GetCell", row, col).Call("GetContent").Call("GetElement", 0);
}
public static void addTextToParagraph(CValue oParagraph, string text, int fontSize, bool isBold)
{
oParagraph.Call("AddText", text);
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetBold", isBold);
}
public static void setPictureFormProperties(CValue oPictureForm, string key, string tip, bool required, string placeholder, string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, string imageUrl)
{
oPictureForm.Call("SetFormKey", key);
oPictureForm.Call("SetTipText", tip);
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder);
oPictureForm.Call("SetScaleFlag", scaleFlag);
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl);
}
public static void setTextFormProperties(CValue oTextForm, string key, string tip, bool required, string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key);
oTextForm.Call("SetTipText", tip);
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder);
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
public static void addTextFormToParagraph(CValue oParagraph, CValue oTextForm, int fontSize, string jc, bool hasBorder, int borderColor)
{
if (hasBorder)
{
oTextForm.Call("SetBorderColor", borderColor, borderColor, borderColor);
}
oParagraph.Call("AddElement", oTextForm);
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetJc", jc);
}
}
}

View File

@ -0,0 +1,123 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CreatingBasicForm
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.docx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreateBasicForm(workDirectory, resultPath);
}
public static void CreateBasicForm(string workDirectory, string resultPath)
{
var doctype = (int)OfficeFileTypes.Document.DOCX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create basic form
CValue oDocument = oApi.Call("GetDocument");
CValue oParagraph = oDocument.Call("GetElement", 0);
CValue oHeadingStyle = oDocument.Call("GetStyle", "Heading 3");
oParagraph.Call("AddText", "Employee pass card");
oParagraph.Call("SetStyle", oHeadingStyle);
oDocument.Call("Push", oParagraph);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload your photo", false, "Photo", "tooBig", true, false, 50, 50, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "First name", "Enter your first name", false, "First name", true, 13, 3, false, false);
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oTextForm);
oDocument.Call("Push", oParagraph);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static void setPictureFormProperties(CValue oPictureForm, string key, string tip, bool required, string placeholder, string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, string imageUrl)
{
oPictureForm.Call("SetFormKey", key);
oPictureForm.Call("SetTipText", tip);
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder);
oPictureForm.Call("SetScaleFlag", scaleFlag);
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl);
}
public static void setTextFormProperties(CValue oTextForm, string key, string tip, bool required, string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key);
oTextForm.Call("SetTipText", tip);
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder);
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
}
}

View File

@ -0,0 +1,196 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CreatingChartPresentation
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.pptx";
string filePath = "../../../../../../resources/docs/chart_data.xlsx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreateChartPresentation(workDirectory, resultPath, filePath);
}
public static void CreateChartPresentation(string workDirectory, string resultPath, string filePath)
{
var doctype = (int)OfficeFileTypes.Presentation.PPTX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
// Read chart data from xlsx
oBuilder.OpenFile(filePath, "xlsx");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue oRange = oWorksheet.Call("GetUsedRange").Call("GetValue");
object[,] array = oRangeTo2dArray(oRange, oContext);
oBuilder.CloseFile();
// Create chart presentation
oBuilder.CreateFile(doctype);
oContext = oBuilder.GetContext();
oScope = oContext.CreateScope();
oGlobal = oContext.GetGlobal();
oApi = oGlobal["Api"];
CValue oPresentation = oApi.Call("GetPresentation");
CValue oSlide = oPresentation.Call("GetSlideByIndex", 0);
oSlide.Call("RemoveAllObjects");
CValue oRGBColor = oApi.Call("CreateRGBColor", 255, 244, 240);
CValue oFill = oApi.Call("CreateSolidFill", oRGBColor);
oSlide.Call("SetBackground", oFill);
CValue oStroke = oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill"));
CValue oShapeTitle = oApi.Call("CreateShape", "rect", 300 * 36000, 20 * 36000, oApi.Call("CreateNoFill"), oStroke);
CValue oShapeText = oApi.Call("CreateShape", "rect", 120 * 36000, 80 * 36000, oApi.Call("CreateNoFill"), oStroke);
oShapeTitle.Call("SetPosition", 20 * 36000, 20 * 36000);
oShapeText.Call("SetPosition", 210 * 36000, 50 * 36000);
CValue oParagraphTitle = oShapeTitle.Call("GetDocContent").Call("GetElement", 0);
CValue oParagraphText = oShapeText.Call("GetDocContent").Call("GetElement", 0);
oRGBColor = oApi.Call("CreateRGBColor", 115, 81, 68);
oFill = oApi.Call("CreateSolidFill", oRGBColor);
string titleContent = "Price Type Report";
string textContent = "This is an overview of price types. As we can see, May was the price peak, but even in June the price went down, the annual upward trend persists.";
addText(oApi, 80, titleContent, oSlide, oShapeTitle, oParagraphTitle, oFill, "center");
addText(oApi, 42, textContent, oSlide, oShapeText, oParagraphText, oFill, "left");
// Transform 2d array into cols names, rows names and data
CValue array_cols = colsFromArray(array, oContext);
CValue array_rows = rowsFromArray(array, oContext);
CValue array_data = dataFromArray(array, oContext);
// Pass CValue data to the CreateChart method
CValue oChart = oApi.Call("CreateChart", "lineStacked", array_data, array_cols, array_rows);
oChart.Call("SetSize", 180 * 36000, 100 * 36000);
oChart.Call("SetPosition", 20 * 36000, 50 * 36000);
oChart.Call("ApplyChartStyle", 24);
oChart.Call("SetVertAxisLabelsFontSize", 16);
oChart.Call("SetHorAxisLabelsFontSize", 16);
oChart.Call("SetLegendFontSize", 16);
oChart.Call("SetLegendPos", "top");
oSlide.Call("AddObject", oChart);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static object[,] oRangeTo2dArray(CValue oRange, CContext oContext)
{
int rowsLen = (int)oRange.GetLength();
int colsLen = (int)oRange[0].GetLength();
object[,] oArray = new object[rowsLen, colsLen];
for (int col = 0; col < colsLen; col++)
{
CValue oArrayRow = oContext.CreateArray(rowsLen);
for (int row = 0; row < rowsLen; row++)
{
oArray[row, col] = oRange[row][col].ToString();
}
}
return oArray;
}
public static CValue colsFromArray(object[,] array, CContext oContext)
{
int colsLen = array.GetLength(1) - 1;
CValue cols = oContext.CreateArray(colsLen);
for (int col = 1; col <= colsLen; col++)
{
cols[col - 1] = array[0, col].ToString();
}
return cols;
}
public static CValue rowsFromArray(object[,] array, CContext oContext)
{
int rowsLen = array.GetLength(0) - 1;
CValue rows = oContext.CreateArray(rowsLen);
for (int row = 1; row <= rowsLen; row++)
{
rows[row - 1] = array[row, 0].ToString();
}
return rows;
}
public static CValue dataFromArray(object[,] array, CContext oContext)
{
int colsLen = array.GetLength(0) - 1;
int rowsLen = array.GetLength(1) - 1;
CValue data = oContext.CreateArray(rowsLen);
for (int row = 1; row <= rowsLen; row++)
{
CValue row_data = oContext.CreateArray(colsLen);
for (int col = 1; col <= colsLen; col++)
{
row_data[col - 1] = array[col, row].ToString();
}
data[row - 1] = row_data;
}
return data;
}
public static void addText(CValue oApi, int fontSize, string text, CValue oSlide, CValue oShape, CValue oParagraph, CValue oFill, string jc)
{
CValue oRun = oApi.Call("CreateRun");
var oTextPr = oRun.Call("GetTextPr");
oTextPr.Call("SetFontSize", fontSize);
oTextPr.Call("SetFill", oFill);
oTextPr.Call("SetFontFamily", "Tahoma");
oParagraph.Call("SetJc", jc);
oRun.Call("AddText", text);
oRun.Call("AddLineBreak");
oParagraph.Call("AddElement", oRun);
oSlide.Call("AddObject", oShape);
}
}
}

View File

@ -0,0 +1,168 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
using System.Collections.Generic;
namespace Sample
{
public class CreatingPresentation
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.pptx";
IDictionary<string, string> slideImages = new Dictionary<string, string>() {
{ "gun", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png" },
{ "axe","https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png" },
{ "knight", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png" },
{ "sky","https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png" }
};
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreatePresentation(workDirectory, resultPath, slideImages);
}
public static void CreatePresentation(string workDirectory, string resultPath, IDictionary<string, string> slideImages)
{
var doctype = (int)OfficeFileTypes.Presentation.PPTX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
// Create presentation
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oPresentation = oApi.Call("GetPresentation");
oPresentation.Call("SetSizes", 9144000, 6858000);
CValue oSlide = createImageSlide(oApi, oPresentation, slideImages["gun"]);
oPresentation.Call("GetSlideByIndex", 0).Call("Delete");
CValue oShape = oApi.Call("CreateShape", "rect", 8056800, 3020400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 608400, 1267200);
CValue oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "How They", 160, true, "left");
addTextToSlideShape(oApi, oContent, "Throw Out", 132, false, "left");
addTextToSlideShape(oApi, oContent, "a Challenge", 132, false, "left");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["axe"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "American Indians ", 110, true, "right");
addTextToSlideShape(oApi, oContent, "(XVII century)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "put a tomahawk on the ground in the ", 84, false, "right");
addTextToSlideShape(oApi, oContent, "rival's camp", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["knight"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "European Knights", 110, true, "right");
addTextToSlideShape(oApi, oContent, " (XII-XVI centuries)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "threw a glove", 84, false, "right");
addTextToSlideShape(oApi, oContent, "in the rival's face", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["sky"]);
oShape = oApi.Call("CreateShape", "rect", 7887600, 3063600, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 630000, 1357200);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "OnlyOffice", 176, false, "center");
addTextToSlideShape(oApi, oContent, "stands for Peace", 132, false, "center");
oSlide.Call("AddObject", oShape);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static CValue createImageSlide(CValue oApi, CValue oPresentation, string image_url)
{
CValue oSlide = oApi.Call("CreateSlide");
oPresentation.Call("AddSlide", oSlide);
var oFill = oApi.Call("CreateBlipFill", image_url, "stretch");
oSlide.Call("SetBackground", oFill);
oSlide.Call("RemoveAllObjects");
return oSlide;
}
public static void addTextToSlideShape(CValue oApi, CValue oContent, string text, int fontSize, bool isBold, string js)
{
var oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("SetSpacingBefore", 0);
oParagraph.Call("SetSpacingAfter", 0);
oContent.Call("Push", oParagraph);
var oRun = oParagraph.Call("AddText", text);
oRun.Call("SetFill", oApi.Call("CreateSolidFill", oApi.Call("CreateRGBColor", 0xff, 0xff, 0xff)));
oRun.Call("SetFontSize", fontSize);
oRun.Call("SetFontFamily", "Georgia");
oRun.Call("SetBold", isBold);
oParagraph.Call("SetJc", js);
}
}
}

View File

@ -0,0 +1,115 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
using System;
using System.Collections.Generic;
namespace Sample
{
public class FillingForm
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string filePath = "../../../../../../resources/docs/form.docx";
string resultPath = "../../../result.docx";
IDictionary<string, string> formData = new Dictionary<string, string>() {
{ "Photo", "https://api.onlyoffice.com/content/img/docbuilder/examples/blue_cloud.png" },
{ "Serial","A1345" },
{ "Company Name", "Blue Cloud" },
{ "Date", "25.12.2023" },
{ "Recipient", "Space Corporation" },
{ "Qty1", "25" },
{ "Description1", "Frame" },
{ "Qty2", "2" },
{ "Description2", "Stack" },
{ "Qty3", "34" },
{ "Description3", "Shifter" }
};
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
FillForm(workDirectory, resultPath, filePath, formData);
}
public static void FillForm(string workDirectory, string resultPath, string filePath, IDictionary<string, string> formData)
{
var doctype = (int)OfficeFileTypes.Document.DOCX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.OpenFile(filePath, "docxf");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Fill form
CValue oDocument = oApi.Call("GetDocument");
CValue aForms = oDocument.Call("GetAllForms");
int formNum = 0;
while (formNum < aForms.GetLength())
{
CValue form = aForms[formNum];
string type = form.Call("GetFormType").ToString();
string value;
try
{
value = formData[form.Call("GetFormKey").ToString()];
}
catch (Exception e)
{
value = "";
}
if (type == "textForm") form.Call("SetText", value);
if (type == "pictureForm") form.Call("SetImage", value);
formNum++;
}
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
}
}

View File

@ -0,0 +1,114 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class FillingSpreadsheet
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.xlsx";
object[,] data = {
{ "Id", "Product", "Price", "Available"},
{ 1001, "Item A", 12.2, true },
{ 1002, "Item B", 18.8, true },
{ 1003, "Item C", 70.1, false },
{ 1004, "Item D", 60.6, true },
{ 1005, "Item E", 32.6, true },
{ 1006, "Item F", 28.3, false },
{ 1007, "Item G", 11.1, false },
{ 1008, "Item H", 41.4, true }
};
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
FillSpreadsheet(workDirectory, resultPath, data);
}
public static void FillSpreadsheet(string workDirectory, string resultPath, object[,] data)
{
var doctype = (int)OfficeFileTypes.Spreadsheet.XLSX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oWorksheet = oApi.Call("GetActiveSheet");
// pass data
CValue oArray = TwoDimArrayToCValue(data, oContext);
// First cell in the range (A1) is equal to (0,0)
CValue startCell = oWorksheet.Call("GetRangeByNumber", 0, 0);
// Last cell in the range is equal to array length -1
CValue endCell = oWorksheet.Call("GetRangeByNumber", oArray.GetLength() - 1, oArray[0].GetLength() - 1);
oWorksheet.Call("GetRange", startCell, endCell).Call("SetValue", oArray);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static CValue TwoDimArrayToCValue(object[,] data, CContext oContext)
{
int rowsLen = data.GetLength(0);
int colsLen = data.GetLength(1);
CValue oArray = oContext.CreateArray(rowsLen);
for (int row = 0; row < rowsLen; row++)
{
CValue oArrayCol = oContext.CreateArray(colsLen);
for (int col = 0; col < colsLen; col++)
{
oArrayCol[col] = data[row, col].ToString();
}
oArray[row] = oArrayCol;
}
return oArray;
}
}
}

View File

@ -0,0 +1,76 @@
import docbuilder.*;
public class Program {
public static void main(String[] args) {
String resultPath = "result.docx";
createBasicForm(resultPath);
// Need to explicitly call System.gc() to free up resources
System.gc();
}
public static void createBasicForm(String resultPath) {
int doctype = FileTypes.Document.DOCX;
// Initialize builder with docbuilder.jar directory by passing empty string
CDocBuilder.initialize("");
CDocBuilder builder = new CDocBuilder();
builder.createFile(doctype);
CDocBuilderContext context = builder.getContext();
CDocBuilderValue global = context.getGlobal();
CDocBuilderValue api = global.get("Api");
// Create basic form
CDocBuilderValue document = api.call("GetDocument");
CDocBuilderValue paragraph = document.call("GetElement", 0);
CDocBuilderValue headingStyle = document.call("GetStyle", "Heading 3");
paragraph.call("AddText", "Employee pass card");
paragraph.call("SetStyle", headingStyle);
document.call("Push", paragraph);
CDocBuilderValue pictureForm = api.call("CreatePictureForm");
setPictureFormProperties(pictureForm, "Photo", "Upload your photo", false, "Photo", "tooBig", true, false, 50, 50, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
paragraph = api.call("CreateParagraph");
paragraph.call("AddElement", pictureForm);
document.call("Push", paragraph);
CDocBuilderValue textForm = api.call("CreateTextForm");
setTextFormProperties(textForm, "First name", "Enter your first name", false, "First name", true, 13, 3, false, false);
paragraph = api.call("CreateParagraph");
paragraph.call("AddElement", textForm);
document.call("Push", paragraph);
// Save file and close DocBuilder
builder.saveFile(doctype, resultPath);
builder.closeFile();
CDocBuilder.dispose();
}
public static void setPictureFormProperties(CDocBuilderValue pictureForm, String key, String tip, boolean required, String placeholder, String scaleFlag, boolean lockAspectRatio, boolean respectBorders, int shiftX, int shiftY, String imageUrl) {
pictureForm.call("SetFormKey", key);
pictureForm.call("SetTipText", tip);
pictureForm.call("SetRequired", required);
pictureForm.call("SetPlaceholderText", placeholder);
pictureForm.call("SetScaleFlag", scaleFlag);
pictureForm.call("SetLockAspectRatio", lockAspectRatio);
pictureForm.call("SetRespectBorders", respectBorders);
pictureForm.call("SetPicturePosition", shiftX, shiftY);
pictureForm.call("SetImage", imageUrl);
}
public static void setTextFormProperties(CDocBuilderValue textForm, String key, String tip, boolean required, String placeholder, boolean comb, int maxCharacters, int cellWidth, boolean multiLine, boolean autoFit) {
textForm.call("SetFormKey", key);
textForm.call("SetTipText", tip);
textForm.call("SetRequired", required);
textForm.call("SetPlaceholderText", placeholder);
textForm.call("SetComb", comb);
textForm.call("SetCharactersLimit", maxCharacters);
textForm.call("SetCellWidth", cellWidth);
textForm.call("SetCellWidth", multiLine);
textForm.call("SetMultiline", autoFit);
}
}

View File

@ -0,0 +1,123 @@
import docbuilder.*;
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
String resultPath = "result.pptx";
// Fill slide images
HashMap<String, String> slideImages = new HashMap<String, String>();
slideImages.put("gun", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png");
slideImages.put("axe", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png");
slideImages.put("knight", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png");
slideImages.put("sky", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png");
createPresentation(resultPath, slideImages);
// Need to explicitly call System.gc() to free up resources
System.gc();
}
public static void createPresentation(String resultPath, HashMap<String, String> slideImages) {
int doctype = FileTypes.Presentation.PPTX;
// Initialize builder with docbuilder.jar directory by passing empty String
CDocBuilder.initialize("");
CDocBuilder builder = new CDocBuilder();
builder.createFile(doctype);
CDocBuilderContext context = builder.getContext();
CDocBuilderValue global = context.getGlobal();
CDocBuilderValue api = global.get("Api");
// Create presentation
CDocBuilderValue presentation = api.call("GetPresentation");
presentation.call("SetSizes", 9144000, 6858000);
CDocBuilderValue slide = createImageSlide(api, presentation, slideImages.get("gun"));
presentation.call("GetSlideByIndex", 0).call("Delete");
CDocBuilderValue shape = api.call("CreateShape", "rect", 8056800, 3020400, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 608400, 1267200);
CDocBuilderValue content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "How They", 160, true, "left");
addTextToSlideShape(api, content, "Throw Out", 132, false, "left");
addTextToSlideShape(api, content, "a Challenge", 132, false, "left");
slide.call("AddObject", shape);
slide = createImageSlide(api, presentation, slideImages.get("axe"));
shape = api.call("CreateShape", "rect", 6904800, 1724400, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 1764000, 1191600);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "American Indians ", 110, true, "right");
addTextToSlideShape(api, content, "(XVII century)", 94, false, "right");
slide.call("AddObject", shape);
shape = api.call("CreateShape", "rect", 4986000, 2419200, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 3834000, 3888000);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "put a tomahawk on the ground in the ", 84, false, "right");
addTextToSlideShape(api, content, "rival's camp", 84, false, "right");
slide.call("AddObject", shape);
slide = createImageSlide(api, presentation, slideImages.get("knight"));
shape = api.call("CreateShape", "rect", 6904800, 1724400, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 1764000, 1191600);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "European Knights", 110, true, "right");
addTextToSlideShape(api, content, " (XII-XVI centuries)", 94, false, "right");
slide.call("AddObject", shape);
shape = api.call("CreateShape", "rect", 4986000, 2419200, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 3834000, 3888000);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "threw a glove", 84, false, "right");
addTextToSlideShape(api, content, "in the rival's face", 84, false, "right");
slide.call("AddObject", shape);
slide = createImageSlide(api, presentation, slideImages.get("sky"));
shape = api.call("CreateShape", "rect", 7887600, 3063600, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 630000, 1357200);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "OnlyOffice", 176, false, "center");
addTextToSlideShape(api, content, "stands for Peace", 132, false, "center");
slide.call("AddObject", shape);
// Save file and close DocBuilder
builder.saveFile(doctype, resultPath);
builder.closeFile();
CDocBuilder.dispose();
}
public static CDocBuilderValue createImageSlide(CDocBuilderValue api, CDocBuilderValue presentation, String imageUrl) {
CDocBuilderValue slide = api.call("CreateSlide");
presentation.call("AddSlide", slide);
CDocBuilderValue fill = api.call("CreateBlipFill", imageUrl, "stretch");
slide.call("SetBackground", fill);
slide.call("RemoveAllObjects");
return slide;
}
public static void addTextToSlideShape(CDocBuilderValue api, CDocBuilderValue content, String text, int fontSize, boolean isBold, String js) {
CDocBuilderValue paragraph = api.call("CreateParagraph");
paragraph.call("SetSpacingBefore", 0);
paragraph.call("SetSpacingAfter", 0);
content.call("Push", paragraph);
CDocBuilderValue run = paragraph.call("AddText", text);
run.call("SetFill", api.call("CreateSolidFill", api.call("CreateRGBColor", 0xff, 0xff, 0xff)));
run.call("SetFontSize", fontSize);
run.call("SetFontFamily", "Georgia");
run.call("SetBold", isBold);
paragraph.call("SetJc", js);
}
}

View File

@ -0,0 +1,54 @@
import docbuilder.*;
public class Program {
public static void main(String[] args) {
String resultPath = "result.xlsx";
// Fill table data
Object[][] data = {
{ "Id", "Product", "Price", "Available" },
{ 1001, "Item A", 12.2, true },
{ 1002, "Item B", 18.8, true },
{ 1003, "Item C", 70.1, false },
{ 1004, "Item D", 60.6, true },
{ 1005, "Item E", 32.6, true },
{ 1006, "Item F", 28.3, false },
{ 1007, "Item G", 11.1, false },
{ 1008, "Item H", 41.4, true }
};
fillSpreadsheet(resultPath, data);
// Need to explicitly call System.gc() to free up resources
System.gc();
}
public static void fillSpreadsheet(String resultPath, Object[][] data) {
int doctype = FileTypes.Spreadsheet.XLSX;
// Initialize builder with docbuilder.jar directory by passing empty String
CDocBuilder.initialize("");
CDocBuilder builder = new CDocBuilder();
builder.createFile(doctype);
CDocBuilderContext context = builder.getContext();
CDocBuilderValue global = context.getGlobal();
CDocBuilderValue api = global.get("Api");
// Create spreadsheet
CDocBuilderValue worksheet = api.call("GetActiveSheet");
// Convert data to array value type
CDocBuilderValue array = new CDocBuilderValue(data);
// First cell in the range (A1) is equal to (0,0)
CDocBuilderValue startCell = worksheet.call("GetRangeByNumber", 0, 0);
// Last cell in the range is equal to array length -1
CDocBuilderValue endCell = worksheet.call("GetRangeByNumber", array.getLength() - 1, array.get(0).getLength() - 1);
worksheet.call("GetRange", startCell, endCell).call("SetValue", array);
// Save file and close DocBuilder
builder.saveFile(doctype, resultPath);
builder.closeFile();
CDocBuilder.dispose();
}
}

View File

@ -0,0 +1,60 @@
import os
import sys
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
# Helper functions
def setPictureFormProperties(pictureForm, key, tip, required, placeholder, scaleFlag, lockAspectRatio, respectBorders, shiftX, shiftY, imageUrl):
pictureForm.Call('SetFormKey', key)
pictureForm.Call('SetTipText', tip)
pictureForm.Call('SetRequired', required)
pictureForm.Call('SetPlaceholderText', placeholder)
pictureForm.Call('SetScaleFlag', scaleFlag)
pictureForm.Call('SetLockAspectRatio', lockAspectRatio)
pictureForm.Call('SetRespectBorders', respectBorders)
pictureForm.Call('SetPicturePosition', shiftX, shiftY)
pictureForm.Call('SetImage', imageUrl)
def setTextFormProperties(textForm, key, tip, required, placeholder, comb, maxCharacters, cellWidth, multiLine, autoFit):
textForm.Call('SetFormKey', key)
textForm.Call('SetTipText', tip)
textForm.Call('SetRequired', required)
textForm.Call('SetPlaceholderText', placeholder)
textForm.Call('SetComb', comb)
textForm.Call('SetCharactersLimit', maxCharacters)
textForm.Call('SetCellWidth', cellWidth)
textForm.Call('SetCellWidth', multiLine)
textForm.Call('SetMultiline', autoFit)
if __name__ == '__main__':
builder = docbuilder.CDocBuilder()
builder.CreateFile(docbuilder.FileTypes.Document.DOCX)
context = builder.GetContext()
globalObj = context.GetGlobal()
api = globalObj['Api']
document = api.Call('GetDocument')
paragraph = document.Call('GetElement', 0)
headingStyle = document.Call('GetStyle', 'Heading 3')
paragraph.Call('AddText', 'Employee pass card')
paragraph.Call('SetStyle', headingStyle)
document.Call('Push', paragraph)
pictureForm = api.Call('CreatePictureForm')
setPictureFormProperties(pictureForm, 'Photo', 'Upload your photo', False, 'Photo', 'tooBig', True, False, 50, 50, 'https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png')
paragraph = api.Call('CreateParagraph')
paragraph.Call('AddElement', pictureForm)
document.Call('Push', paragraph)
textForm = api.Call('CreateTextForm')
setTextFormProperties(textForm, 'First name', 'Enter your first name', False, 'First name', True, 13, 3, False, False)
paragraph = api.Call('CreateParagraph')
paragraph.Call('AddElement', textForm)
document.Call('Push', paragraph)
# Save and close
resultPath = os.getcwd() + '/result.docx'
builder.SaveFile(docbuilder.FileTypes.Document.DOCX, resultPath)
builder.CloseFile()

View File

@ -0,0 +1,105 @@
import os
import sys
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
def createImageSlide(api, presentation, image_url):
slide = api.Call('CreateSlide')
presentation.Call('AddSlide', slide)
fill = api.Call('CreateBlipFill', image_url, 'stretch')
slide.Call('SetBackground', fill)
slide.Call('RemoveAllObjects')
return slide
def addTextToSlideShape(api, content, text, fontSize, isBold, js):
paragraph = api.Call('CreateParagraph')
paragraph.Call('SetSpacingBefore', 0)
paragraph.Call('SetSpacingAfter', 0)
content.Call('Push', paragraph)
run = paragraph.Call('AddText', text)
run.Call('SetFill', api.Call('CreateSolidFill', api.Call('CreateRGBColor', 0xff, 0xff, 0xff)))
run.Call('SetFontSize', fontSize)
run.Call('SetFontFamily', 'Georgia')
run.Call('SetBold', isBold)
paragraph.Call('SetJc', js)
if __name__ == '__main__':
slideImages = {}
slideImages['gun'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png'
slideImages['axe'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png'
slideImages['knight'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png'
slideImages['sky'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png'
builder = docbuilder.CDocBuilder()
builder.CreateFile(docbuilder.FileTypes.Presentation.PPTX)
context = builder.GetContext()
globalObj = context.GetGlobal()
api = globalObj['Api']
# Create presentation
presentation = api.Call('GetPresentation')
presentation.Call('SetSizes', 9144000, 6858000)
slide = createImageSlide(api, presentation, slideImages['gun'])
presentation.Call('GetSlideByIndex', 0).Call('Delete')
shape = api.Call('CreateShape', 'rect', 8056800, 3020400, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 608400, 1267200)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'How They', 160, True, 'left')
addTextToSlideShape(api, content, 'Throw Out', 132, False, 'left')
addTextToSlideShape(api, content, 'a Challenge', 132, False, 'left')
slide.Call('AddObject', shape)
slide = createImageSlide(api, presentation, slideImages['axe'])
shape = api.Call('CreateShape', 'rect', 6904800, 1724400, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 1764000, 1191600)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'American Indians ', 110, True, 'right')
addTextToSlideShape(api, content, '(XVII century)', 94, False, 'right')
slide.Call('AddObject', shape)
shape = api.Call('CreateShape', 'rect', 4986000, 2419200, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 3834000, 3888000)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'put a tomahawk on the ground in the ', 84, False, 'right')
addTextToSlideShape(api, content, 'rival\'s camp', 84, False, 'right')
slide.Call('AddObject', shape)
slide = createImageSlide(api, presentation, slideImages['knight'])
shape = api.Call('CreateShape', 'rect', 6904800, 1724400, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 1764000, 1191600)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'European Knights', 110, True, 'right')
addTextToSlideShape(api, content, ' (XII-XVI centuries)', 94, False, 'right')
slide.Call('AddObject', shape)
shape = api.Call('CreateShape', 'rect', 4986000, 2419200, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 3834000, 3888000)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'threw a glove', 84, False, 'right')
addTextToSlideShape(api, content, 'in the rival\'s face', 84, False, 'right')
slide.Call('AddObject', shape)
slide = createImageSlide(api, presentation, slideImages['sky'])
shape = api.Call('CreateShape', 'rect', 7887600, 3063600, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 630000, 1357200)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'OnlyOffice', 176, False, 'center')
addTextToSlideShape(api, content, 'stands for Peace', 132, False, 'center')
slide.Call('AddObject', shape)
# Save and close
resultPath = os.getcwd() + '/result.pptx'
builder.SaveFile(docbuilder.FileTypes.Presentation.PPTX, resultPath)
builder.CloseFile()

View File

@ -0,0 +1,42 @@
import os
import sys
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
if __name__ == '__main__':
data = [
[ 'Id', 'Product', 'Price', 'Available' ],
[ '1001', 'Item A', "12.2", 'true' ],
[ '1002', 'Item B', "18.8", 'true' ],
[ '1003', 'Item C', "70.1", 'false' ],
[ '1004', 'Item D', "60.6", 'true' ],
[ '1005', 'Item E', "32.6", 'true' ],
[ '1006', 'Item F', "28.3", 'false' ],
[ '1007', 'Item G', "11.1", 'false' ],
[ '1008', 'Item H', "41.4", 'true' ]
]
builder = docbuilder.CDocBuilder()
builder.CreateFile(docbuilder.FileTypes.Spreadsheet.XLSX)
context = builder.GetContext()
globalObj = context.GetGlobal()
api = globalObj['Api']
# Find and comment formula errors
worksheet = api.Call('GetActiveSheet')
# Create array from data
array = docbuilder.CDocBuilderValue(data)
# First cell in the range (A1) is equal to (0,0)
startCell = worksheet.Call('GetRangeByNumber', 0, 0)
# Last cell in the range is equal to array length -1
endCell = worksheet.Call('GetRangeByNumber', len(data) - 1, len(data[0]) - 1)
worksheet.Call('GetRange', startCell, endCell).Call('SetValue', array)
# Save and close
resultPath = os.getcwd() + '/result.xlsx'
builder.SaveFile(docbuilder.FileTypes.Spreadsheet.XLSX, resultPath)
builder.CloseFile()

View File

@ -0,0 +1,258 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
// convenient macro definitions
#if defined(__linux__) || defined(__linux)
#define _LINUX
#elif defined(__APPLE__) || defined(__MACH__)
#define _MAC
#endif
#include <string>
#ifdef _WIN32
#include <wchar.h>
#include <windows.h>
#endif
#if defined(_LINUX) || defined(_MAC)
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#endif
#ifdef _MAC
#include <mach-o/dyld.h>
#endif
#ifdef CreateFile
#undef CreateFile
#endif
namespace NSUtils
{
#ifdef _WIN32
#define PATH_SEPARATOR '\\'
#define WriteCodepoint(code) \
if (code < 0x10000) \
*unicodes_cur++ = code; \
else \
{ \
code -= 0x10000; \
*unicodes_cur++ = 0xD800 | ((code >> 10) & 0x03FF); \
*unicodes_cur++ = 0xDC00 | (code & 0x03FF); \
}
#else
#define PATH_SEPARATOR '/'
#define WriteCodepoint(code) *unicodes_cur++ = (wchar_t)code;
#endif
std::wstring GetStringFromUtf8(const unsigned char* utf8, size_t length)
{
wchar_t* unicodes = new wchar_t[length + 1];
wchar_t* unicodes_cur = unicodes;
size_t index = 0;
while (index < length)
{
unsigned char byteMain = utf8[index];
if (0x00 == (byteMain & 0x80))
{
// 1 byte
WriteCodepoint(byteMain)
++index;
}
else if (0x00 == (byteMain & 0x20))
{
// 2 byte
int val = 0;
if ((index + 1) < length)
{
val = (int)(((byteMain & 0x1F) << 6) |
(utf8[index + 1] & 0x3F));
}
WriteCodepoint(val)
index += 2;
}
else if (0x00 == (byteMain & 0x10))
{
// 3 byte
int val = 0;
if ((index + 2) < length)
{
val = (int)(((byteMain & 0x0F) << 12) |
((utf8[index + 1] & 0x3F) << 6) |
(utf8[index + 2] & 0x3F));
}
WriteCodepoint(val)
index += 3;
}
else if (0x00 == (byteMain & 0x0F))
{
// 4 byte
int val = 0;
if ((index + 3) < length)
{
val = (int)(((byteMain & 0x07) << 18) |
((utf8[index + 1] & 0x3F) << 12) |
((utf8[index + 2] & 0x3F) << 6) |
(utf8[index + 3] & 0x3F));
}
WriteCodepoint(val)
index += 4;
}
else if (0x00 == (byteMain & 0x08))
{
// 4 byte
int val = 0;
if ((index + 3) < length)
{
val = (int)(((byteMain & 0x07) << 18) |
((utf8[index + 1] & 0x3F) << 12) |
((utf8[index + 2] & 0x3F) << 6) |
(utf8[index + 3] & 0x3F));
}
WriteCodepoint(val)
index += 4;
}
else if (0x00 == (byteMain & 0x04))
{
// 5 byte
int val = 0;
if ((index + 4) < length)
{
val = (int)(((byteMain & 0x03) << 24) |
((utf8[index + 1] & 0x3F) << 18) |
((utf8[index + 2] & 0x3F) << 12) |
((utf8[index + 3] & 0x3F) << 6) |
(utf8[index + 4] & 0x3F));
}
WriteCodepoint(val)
index += 5;
}
else
{
// 6 byte
int val = 0;
if ((index + 5) < length)
{
val = (int)(((byteMain & 0x01) << 30) |
((utf8[index + 1] & 0x3F) << 24) |
((utf8[index + 2] & 0x3F) << 18) |
((utf8[index + 3] & 0x3F) << 12) |
((utf8[index + 4] & 0x3F) << 6) |
(utf8[index + 5] & 0x3F));
}
WriteCodepoint(val)
index += 5;
}
}
*unicodes_cur++ = 0;
std::wstring sOutput(unicodes);
delete[] unicodes;
return sOutput;
}
}
namespace NSUtils
{
#define NS_FILE_MAX_PATH 32768
std::wstring GetProcessPath()
{
#ifdef _WIN32
wchar_t buf [NS_FILE_MAX_PATH];
GetModuleFileNameW(GetModuleHandle(NULL), buf, NS_FILE_MAX_PATH);
return std::wstring(buf);
#endif
#if defined(_LINUX) || defined(_MAC)
char buf[NS_FILE_MAX_PATH];
memset(buf, 0, NS_FILE_MAX_PATH);
if (readlink ("/proc/self/exe", buf, NS_FILE_MAX_PATH) <= 0)
{
#ifdef _MAC
uint32_t _size = NS_FILE_MAX_PATH;
_NSGetExecutablePath(buf, &_size);
#endif
}
return GetStringFromUtf8((unsigned char*)buf, strlen(buf));
#endif
}
std::wstring GetProcessDirectory()
{
std::wstring path = GetProcessPath();
size_t pos = path.find_last_of(PATH_SEPARATOR);
if (pos != std::wstring::npos)
path = path.substr(0, pos);
return path;
}
std::wstring GetResourcesDirectory()
{
std::wstring path = GetProcessDirectory();
while (!path.empty())
{
size_t pos = path.find_last_of(PATH_SEPARATOR);
if (pos != std::wstring::npos)
{
std::wstring currDir = path.substr(pos + 1);
if (currDir == L"samples")
{
path += PATH_SEPARATOR;
path += L"resources";
break;
}
else
{
path = path.substr(0, pos);
}
}
else
{
path = L"";
}
}
return path;
}
}

View File

@ -109,7 +109,7 @@ FT_Error FT_Load_Glyph_Wrapper( FT_Face face,
FT_Err_Invalid_Reference = 0x86;
*/
if ((bHintsSupport == TRUE) && ((nErr > 0x10 && nErr < 0x28) || nErr == 0x83 || nErr == 0x86))
if ((bHintsSupport == TRUE) && ((nErr > 0x10 && nErr < 0x28) || (nErr >= 0x83 && nErr <= 0x8D)))
{
int nErr2 = FT_Load_Glyph(face, glyph_index, 40970);

View File

@ -249,9 +249,9 @@ double Curve::GetTimeAt(const double& offset) const noexcept
double a = forward ? start : 0,
b = forward ? 1 : start,
rangeLength = GetLength(a, b),
diff = abs(offset) - rangeLength;
diff = fabs(offset) - rangeLength;
if (abs(diff) < EPSILON)
if (fabs(diff) < EPSILON)
return forward ? b : a;
else if (diff > EPSILON)
return MIN;
@ -448,8 +448,8 @@ std::vector<std::pair<double, double>> Curve::GetOverlaps(const Curve& curve) co
: std::pair<double, double>(t2, t1);
if (pairs.empty())
pairs.push_back(pair);
else if (abs(pair.first - pairs[0].first) > TIME_EPSILON &&
abs(pair.second - pairs[0].second) > TIME_EPSILON)
else if (fabs(pair.first - pairs[0].first) > TIME_EPSILON &&
fabs(pair.second - pairs[0].second) > TIME_EPSILON)
pairs.push_back(pair);
}
@ -464,10 +464,10 @@ std::vector<std::pair<double, double>> Curve::GetOverlaps(const Curve& curve) co
Curve o1 = GetPart(pairs[0].first, pairs[1].first),
o2 = curve.GetPart(pairs[0].second, pairs[1].second);
double dox = abs(o2.Segment2.HO.X - o1.Segment2.HO.X),
doy = abs(o2.Segment2.HO.Y - o1.Segment2.HO.Y),
dix = abs(o2.Segment2.HI.X - o1.Segment2.HI.X),
diy = abs(o2.Segment2.HI.Y - o1.Segment2.HI.Y);
double dox = fabs(o2.Segment2.HO.X - o1.Segment2.HO.X),
doy = fabs(o2.Segment2.HO.Y - o1.Segment2.HO.Y),
dix = fabs(o2.Segment2.HI.X - o1.Segment2.HI.X),
diy = fabs(o2.Segment2.HI.Y - o1.Segment2.HI.Y);
if (dox > GEOMETRIC_EPSILON ||
doy > GEOMETRIC_EPSILON ||
@ -578,9 +578,9 @@ int Curve::SolveCubic(double a, double b, double c, double d,
std::vector<double>& roots, const double& mn, const double& mx) const noexcept
{
int count = 0;
double f = max(abs(a), abs(b), abs(c), abs(d));
double f = max(fabs(a), fabs(b), fabs(c), fabs(d));
double x, b1, c2, qd, q;
if (f < 1e-8 || f > 1e8)
if (f != 0 && (f < 1e-8 || f > 1e8))
{
f = pow(2, -round(log2(f)));
a *= f;
@ -589,14 +589,14 @@ int Curve::SolveCubic(double a, double b, double c, double d,
d *= f;
}
if (abs(a) < EPSILON)
if (fabs(a) < EPSILON)
{
a = b;
b1 = c;
c2 = d;
x = MAX;
}
else if (abs(d) <EPSILON)
else if (fabs(d) <EPSILON)
{
b1 = b;
c2 = c;
@ -611,7 +611,7 @@ int Curve::SolveCubic(double a, double b, double c, double d,
q = c2 * x + d;
double t = q / a,
r = pow(abs(t), 1 / 3),
r = pow(fabs(t), 1 / 3),
s = t < 0 ? -1 : 1,
td = -qd / a,
rd = td > 0 ? 1.324717957244746 * std::max(r, sqrt(td)) : r,
@ -629,7 +629,7 @@ int Curve::SolveCubic(double a, double b, double c, double d,
x0 = qd == 0 ? x : x - q / qd / (1 + MACHINE_EPSILON);
} while (s * x0 > s * x);
if (abs(a) * x * x > abs(d / x))
if (fabs(a) * x * x > fabs(d / x))
{
c2 = -d / x;
b1 = (c2 - c) / x;

View File

@ -124,14 +124,14 @@ inline double clamp(const double& value, const double& mn, const double& mx)
inline bool isCollinear(const Aggplus::PointD& p1, const Aggplus::PointD& p2)
{
return abs(p1.X * p2.X + p1.Y * p2.Y) <= sqrt((p1.X * p1.X + p1.Y * p1.Y) * (p2.X * p2.X + p2.Y * p2.Y)) * TRIGANOMETRIC_EPSILON;
return fabs(p1.X * p2.X + p1.Y * p2.Y) <= sqrt((p1.X * p1.X + p1.Y * p1.Y) * (p2.X * p2.X + p2.Y * p2.Y)) * TRIGANOMETRIC_EPSILON;
}
inline int getIterations(const double& a, const double& b)
{
double n1 = 2.0, n2 = 16.0;
return std::max(n1, std::min(n2, ceil(abs(b - a) * 32)));
return std::max(n1, std::min(n2, ceil(fabs(b - a) * 32)));
}
inline double CurveLength(const double& t, const double& ax, const double& bx, const double& cx,
@ -180,7 +180,7 @@ double findRoot(double& length, double& start, const double& offset, const doubl
dx = fx / CurveLength(x, ax, bx, cx, ay, by, cy),
nx = x - dx;
if (abs(dx) < EPSILON)
if (fabs(dx) < EPSILON)
{
x = nx;
break;
@ -340,7 +340,7 @@ inline double getSignedDistance(const double& px, const double& py, double vx, d
inline double getDistance(const double& px, const double& py, const double& vx, const double& vy,
const double& x, const double& y, const bool& asVector)
{
return abs(getSignedDistance(px, py, vx, vy, x, y, asVector));
return fabs(getSignedDistance(px, py, vx, vy, x, y, asVector));
}
inline double getDistance(const double& px, const double& py, const double& vx, const double& vy,
@ -394,7 +394,7 @@ inline double getDiscriminant(const double& a, const double& b, const double& c)
double D = b * b - a * c,
E = b * b + a * c;
if (abs(D) * 3 < E)
if (fabs(D) * 3 < E)
{
std::pair<double, double> ad = split(a),
bd = split(b),
@ -420,10 +420,10 @@ int solveQuadratic(double a, double b, double c, std::vector<double>& roots,
const double& mn, const double& mx)
{
double x1 = MAX, x2 = MAX;
if (abs(a) < EPSILON)
if (fabs(a) < EPSILON)
{
if (abs(b) < EPSILON)
return abs(c) < EPSILON ? -1 : 0;
if (fabs(b) < EPSILON)
return fabs(c) < EPSILON ? -1 : 0;
x1 = -c / b;
}
else
@ -431,10 +431,10 @@ int solveQuadratic(double a, double b, double c, std::vector<double>& roots,
b *= -0.5;
double D = getDiscriminant(a, b, c);
if (D != 0 && abs(D) < MACHINE_EPSILON)
if (D != 0 && fabs(D) < MACHINE_EPSILON)
{
double f = max(abs(a), abs(b), abs(c));
if (f < 1e-8 || f < 1e8)
double f = max(fabs(a), fabs(b), fabs(c));
if ((f != 0) && (f < 1e-8 || f < 1e8))
{
f = pow(2, -round(log2(f)));
a *= f;

View File

@ -177,7 +177,8 @@ namespace MetaFile
std::wstring CEmfLogFont::GetFaceName() const
{
return NSFile::CUtf8Converter::GetWStringFromUTF16(oLogFontEx.oLogFont.ushFaceName, 32);
const std::wstring wsFaceName{NSFile::CUtf8Converter::GetWStringFromUTF16(oLogFontEx.oLogFont.ushFaceName, 32)};
return wsFaceName.substr(0, wsFaceName.find(L'\0'));
}
int CEmfLogFont::GetWeight() const

View File

@ -1640,8 +1640,8 @@ namespace MetaFile
BYTE* pNewBuffer = GetClipedImage(pPixels, nWidth, nHeight, oClipRect);
const unsigned int unWidth = std::min(((unsigned int)fabs(oClipRect.Right - oClipRect.Left)), ((unsigned int)nWidth ));
const unsigned int unHeight = std::min(((unsigned int)fabs(oClipRect.Bottom - oClipRect.Top)), ((unsigned int)nHeight));
const unsigned int unWidth = std::min(((unsigned int)abs(oClipRect.Right - oClipRect.Left)), ((unsigned int)nWidth ));
const unsigned int unHeight = std::min(((unsigned int)abs(oClipRect.Bottom - oClipRect.Top)), ((unsigned int)nHeight));
m_pInterpretator->DrawBitmap(arPoints[0].X, arPoints[0].Y, arPoints[1].X - arPoints[0].X - m_pDC->GetPixelWidth(), arPoints[2].Y - arPoints[0].Y - m_pDC->GetPixelHeight(),
(NULL != pNewBuffer) ? pNewBuffer : pPixels, unWidth, unHeight);
@ -1655,8 +1655,6 @@ namespace MetaFile
oParser.PlayFile();
const TXForm& oXForm{m_pDC->GetTransform()};
TRectD oRect;
oRect.Left = arPoints[0].X;
@ -1671,9 +1669,7 @@ namespace MetaFile
oTempSrcRect.Right = oTempSrcRect.Left + ((dFileWidth > oSrcRect.dWidth) ? oSrcRect.dWidth - GetPixelWidth() : dFileWidth);
oTempSrcRect.Bottom = oTempSrcRect.Top + ((dFileHeight > oSrcRect.dHeight) ? oSrcRect.dHeight - GetPixelHeight() : dFileHeight);
TXForm oTransform;
oTransform.Copy(oXForm);
TXForm oTransform(m_pDC->GetTransform());
oTransform.Dx -= m_oHeader.oFramePx.Left;
oTransform.Dy -= m_oHeader.oFramePx.Top;
@ -3210,8 +3206,6 @@ namespace MetaFile
m_oStream >> oMatrix;
UpdateMatrix(oMatrix);
m_pDC->MultiplyTransform(oMatrix, MWT_SET);
UpdateOutputDC();
}

View File

@ -721,14 +721,14 @@ namespace MetaFile
TEmfXForm oViewportXForm(GetPixelWidth() * dM11, 0, 0, GetPixelHeight() * dM22, oViewPort.lX, oViewPort.lY);
m_oFinalTransform.Init();
m_oFinalTransform.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Init();
m_oFinalTransform2.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
}
void CEmfDC::FixIsotropic()

View File

@ -734,6 +734,10 @@ namespace MetaFile
if (oDestRect != oSrcRect)
{
TRectL oClip = oSrcRect;
oClip.Right = oClip.Left + (std::min)(oClip.Right - oClip.Left, (int)unWidth ) - 1;
oClip.Bottom = oClip.Top + (std::min)(oClip.Bottom - oClip.Top, (int)unHeight) - 1;
BYTE* pNewBuffer = ClipBuffer(pBgra, unWidth, unHeight, oClip);
if (NULL != pNewBuffer)

View File

@ -52,9 +52,9 @@ namespace SVG
return false;
}
bool CFont::Draw(const std::wstring &wsText, double dX, double dY, IRenderer *pRenderer, const CSvgFile *pFile, CommandeMode oMode, const TSvgStyles *pStyles, const CRenderedObject* pContexObject) const
bool CFont::Draw(const std::wstring &wsText, const double& dX, const double& dY, const double& dFontHeight, IRenderer *pRenderer, const CSvgFile *pFile, CommandeMode oMode, const TSvgStyles *pStyles, const CRenderedObject* pContexObject) const
{
if (NULL == pRenderer)
if (NULL == pRenderer || wsText.empty())
return false;
double dM11, dM12, dM21, dM22, dRx, dRy;
@ -64,10 +64,25 @@ namespace SVG
Aggplus::CMatrix oMatrix(dM11, dM12, dM21, dM22, dRx, dRy);
oMatrix.Translate(dX, dY);
pRenderer->SetTransform(dM11, dM12, dM21, -dM22, oMatrix.tx(), oMatrix.ty());
MGlyphsMap::const_iterator itFound;
TBounds oGlyphBounds;
double dGlyphScale = 1.;
#define DrawGlyph(glyphPtr, function) \
const TBounds oGlyphBound{glyphPtr->GetBounds()};\
if (Equals(0., dFontHeight) || Equals(oGlyphBound.m_dBottom, oGlyphBound.m_dTop) || Equals(oGlyphBound.m_dRight, oGlyphBound.m_dLeft)) \
continue; \
dGlyphScale = dFontHeight / 1000.; \
if (!Equals(1., dGlyphScale)) \
{ \
oMatrix.Scale(dGlyphScale, -dGlyphScale); \
pRenderer->SetTransform(oMatrix.sx(), oMatrix.shy(), oMatrix.shx(), oMatrix.sy(), oMatrix.tx(), oMatrix.ty()); \
} \
function; \
if (!Equals(1., dGlyphScale)) \
{ \
oMatrix.Scale(1. / dGlyphScale, -1. / dGlyphScale); \
pRenderer->SetTransform(oMatrix.sx(), oMatrix.shy(), oMatrix.shx(), oMatrix.sy(), oMatrix.tx(), oMatrix.ty()); \
} \
for (wchar_t wchGlyph : wsText)
{
@ -78,12 +93,13 @@ namespace SVG
if (NULL == m_pMissingGlyph)
continue;
m_pMissingGlyph->Draw(pRenderer, pFile, oMode, pStyles, pContexObject);
DrawGlyph(m_pMissingGlyph, m_pMissingGlyph->Draw(pRenderer, pFile, oMode, pStyles, pContexObject))
oMatrix.Translate(m_oHorizAdvX.ToDouble(NSCSS::Pixel), 0);
}
else
{
itFound->second->Draw(pRenderer, pFile, oMode, pStyles, pContexObject);
DrawGlyph(itFound->second, itFound->second->Draw(pRenderer, pFile, oMode, pStyles, pContexObject))
if (!itFound->second->m_oHorizAdvX.Empty())
oMatrix.Translate(itFound->second->m_oHorizAdvX.ToDouble(NSCSS::Pixel), 0);
@ -91,9 +107,7 @@ namespace SVG
oMatrix.Translate(m_oHorizAdvX.ToDouble(NSCSS::Pixel), 0);
}
oMatrix.Translate(std::abs(oGlyphBounds.m_dRight - oGlyphBounds.m_dLeft), 0);
pRenderer->SetTransform(dM11, dM12, dM21, -dM22, oMatrix.tx(), oMatrix.ty());
pRenderer->SetTransform(oMatrix.sx(), oMatrix.shy(), oMatrix.shx(), -oMatrix.sy(), oMatrix.tx(), oMatrix.ty());
}
pRenderer->SetTransform(dM11, dM12, dM21, dM22, dRx, dRy);

View File

@ -43,7 +43,7 @@ namespace SVG
void SetData(const std::map<std::wstring, std::wstring> &mAttributes, unsigned short ushLevel, bool bHardMode) override;
bool Apply(IRenderer* pRenderer, const CSvgFile *pFile, const TBounds &oObjectBounds) override;
bool Draw(const std::wstring& wsText, double dX, double dY, IRenderer* pRenderer, const CSvgFile *pFile, CommandeMode oMode = CommandeModeDraw, const TSvgStyles* pStyles = NULL, const CRenderedObject* pContexObject = NULL) const;
bool Draw(const std::wstring& wsText, const double& dX, const double& dY, const double& dFontHeight, IRenderer* pRenderer, const CSvgFile *pFile, CommandeMode oMode = CommandeModeDraw, const TSvgStyles* pStyles = NULL, const CRenderedObject* pContexObject = NULL) const;
private:
void ParseGlyphs(XmlUtils::CXmlNode& oNode);

View File

@ -128,6 +128,7 @@ namespace SVG
bool AddElement(IPathElement* pElement);
friend class CLine;
friend class CFont;
friend class CPolygon;
friend class CPolyline;

View File

@ -45,6 +45,8 @@ namespace SVG
if (NULL == pTSpan)
return;
m_oStyles = pTSpan->m_oStyles;
if (m_oX.Empty())
{
if (!pTSpan->m_arObjects.empty())
@ -157,18 +159,18 @@ namespace SVG
double dX, dY;
CalculatePosition(dX, dY);
if (!UseExternalFont(pFile, dX, dY, pRenderer, oMode, pOtherStyles))
if (!UseExternalFont(pFile, dX, dY, pRenderer, oMode, pOtherStyles, pContexObject))
{
if (!m_wsText.empty())
{
ApplyFont(pRenderer, dX, dY);
pRenderer->CommandDrawText(m_wsText, dX, dY, 0, 0);
}
for (const CTSpan* pTSpan : m_arObjects)
pTSpan->Draw(pRenderer, pFile, oMode, pOtherStyles, pContexObject);
}
for (const CTSpan* pTSpan : m_arObjects)
pTSpan->Draw(pRenderer, pFile, oMode, pOtherStyles, pContexObject);
EndPath(pRenderer, pFile, oOldMatrix, oMode, pOtherStyles, pContexObject);
return true;
@ -318,7 +320,14 @@ namespace SVG
if (NULL == pFont)
return false;
pFont->Draw(m_wsText, dX, dY, pRenderer, pFile, oMode, pOtherStyles, pContexObject);
TSvgStyles oStyle;
if (NULL != pOtherStyles)
oStyle = *pOtherStyles;
oStyle += m_oStyles;
pFont->Draw(m_wsText, dX, dY, m_oFont.GetSize().ToDouble(NSCSS::Pixel), pRenderer, pFile, oMode, &oStyle, pContexObject);
return true;
}

View File

@ -929,10 +929,16 @@ namespace NSDocxRenderer
pNextLine->m_pLine = pCurrLine;
}
}
else if (!is_font_effect && pCurrCont->IsDuplicate(pNextCont.get(), eVType))
else if (!is_font_effect && pCurrCont->IsDuplicate(pNextCont.get(), eVType, eHType))
{
pNextCont = nullptr;
pCurrCont->m_iNumDuplicates++;
// if (!pCurrCont->m_pFontStyle.get()->bBold)
// {
// CFontStyle font_style = *pCurrCont->m_pFontStyle;
// font_style.bBold = true;
// pCurrCont->m_pFontStyle = m_pFontStyleManager->GetOrAddFontStyle(font_style);
// }
}
}
if (pNextLine && pNextLine->IsCanBeDeleted())
@ -1270,20 +1276,9 @@ namespace NSDocxRenderer
{
for (size_t i = 0; i < m_arTextLines.size(); ++i)
{
auto& pCurrLine = m_arTextLines[i];
if (!pCurrLine)
continue;
for (size_t j = 0; j < pCurrLine->m_arConts.size(); ++j)
{
auto& pCurrCont = pCurrLine->m_arConts[j];
if (!pCurrCont)
continue;
if (pCurrCont->m_iNumDuplicates > 0)
pCurrLine->m_iNumDuplicates = std::max(pCurrLine->m_iNumDuplicates, pCurrCont->m_iNumDuplicates);
}
pCurrLine->MergeConts();
auto& curr_line = m_arTextLines[i];
if (!curr_line) continue;
curr_line->MergeConts();
}
DetermineDominantGraphics();
}
@ -1559,19 +1554,6 @@ namespace NSDocxRenderer
if (!curr_line)
continue;
// если у текущей линии есть дубликаты, то создаем из них шейпы
if (curr_line->m_iNumDuplicates > 0)
{
size_t duplicates = curr_line->m_iNumDuplicates;
m_arShapes.push_back(CreateSingleLineShape(curr_line));
while (duplicates > 0)
{
m_arShapes.push_back(CreateSingleLineShape(curr_line));
duplicates--;
}
continue;
}
// если линия пересекается с предыдущей линией
if (index && m_arTextLines[index - 1])
{

View File

@ -95,12 +95,12 @@ namespace NSDocxRenderer
return eHorizontalCrossingType::hctCurrentOutsideNext;
}
else if (m_dLeft < oSrc->m_dLeft && m_dRight < oSrc->m_dRight &&
(m_dRight >= oSrc->m_dLeft || fabs(m_dRight - oSrc->m_dLeft) < c_dTHE_SAME_STRING_Y_PRECISION_MM))
(m_dRight >= oSrc->m_dLeft || fabs(m_dRight - oSrc->m_dLeft) < c_dTHE_SAME_STRING_X_PRECISION_MM))
{
return eHorizontalCrossingType::hctCurrentLeftOfNext;
}
else if (m_dLeft > oSrc->m_dLeft && m_dRight > oSrc->m_dRight &&
(m_dLeft <= oSrc->m_dRight || fabs(m_dLeft - oSrc->m_dRight) < c_dTHE_SAME_STRING_Y_PRECISION_MM))
(m_dLeft <= oSrc->m_dRight || fabs(m_dLeft - oSrc->m_dRight) < c_dTHE_SAME_STRING_X_PRECISION_MM))
{
return eHorizontalCrossingType::hctCurrentRightOfNext;
}
@ -109,8 +109,8 @@ namespace NSDocxRenderer
{
return eHorizontalCrossingType::hctDublicate;
}
else if (fabs(m_dLeft - oSrc->m_dLeft) < c_dTHE_SAME_STRING_Y_PRECISION_MM &&
fabs(m_dRight - oSrc->m_dRight) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
else if (fabs(m_dLeft - oSrc->m_dLeft) < c_dTHE_SAME_STRING_X_PRECISION_MM &&
fabs(m_dRight - oSrc->m_dRight) < c_dTHE_SAME_STRING_X_PRECISION_MM)
{
return eHorizontalCrossingType::hctLeftAndRightBordersMatch;
}

View File

@ -195,8 +195,7 @@ namespace NSDocxRenderer
(this_top <= other_bot || fabs(this_top - other_bot) < c_dTHE_SAME_STRING_Y_PRECISION_MM))
return eVerticalCrossingType::vctCurrentBelowNext;
else if (this_top == other_top && this_bot == other_bot &&
m_dLeft == pCont->m_dLeft && m_dRight == pCont->m_dRight)
else if (this_top == other_top && this_bot == other_bot)
return eVerticalCrossingType::vctDublicate;
else if (fabs(this_top - other_top) < c_dTHE_SAME_STRING_Y_PRECISION_MM &&
@ -529,11 +528,17 @@ namespace NSDocxRenderer
return ret;
}
bool CContText::IsDuplicate(CContText* pCont, eVerticalCrossingType eVType) const noexcept
bool CContText::IsDuplicate(CContText* pCont, eVerticalCrossingType eVType, eHorizontalCrossingType eHType) const noexcept
{
if (eVType == eVerticalCrossingType::vctDublicate && m_oText == pCont->m_oText)
return true;
return false;
return m_oText == pCont->m_oText &&
eVType == eVerticalCrossingType::vctDublicate &&
eHType == eHorizontalCrossingType::hctDublicate;
// return m_oText == pCont->m_oText &&
// eVType == eVerticalCrossingType::vctDublicate &&
// (eHType == eHorizontalCrossingType::hctDublicate ||
// eHType == eHorizontalCrossingType::hctCurrentLeftOfNext ||
// eHType == eHorizontalCrossingType::hctCurrentRightOfNext);
}
bool CContText::IsOnlySpaces() const

View File

@ -110,7 +110,7 @@ namespace NSDocxRenderer
bool IsEqual(const CContText* pCont) const noexcept;
UINT GetNumberOfFeatures() const noexcept;
bool IsDuplicate(CContText *pCont, eVerticalCrossingType eVType) const noexcept;
bool IsDuplicate(CContText* pCont, eVerticalCrossingType eVType, eHorizontalCrossingType eHType) const noexcept;
bool IsOnlySpaces() const;
double CalculateSpace() const noexcept;

View File

@ -469,7 +469,7 @@ namespace NSDocxRenderer
//CheckFontNameStyle(wsName, L"light");
CheckFontNameStyle(wsName, L"condensedbold");
CheckFontNameStyle(wsName, L"semibold");
if (CheckFontNameStyle(wsName, L"semibold")) bBold = true;
if (CheckFontNameStyle(wsName, L"boldmt")) bBold = true;
if (CheckFontNameStyle(wsName, L"bold")) bBold = true;

View File

@ -61,7 +61,7 @@ _UINT64 MemoryStream::ReadUInt64()
{
_UINT64 rdU64 = 0;
if (m_Data)
if (m_Data && (m_Position + 8 <= m_Size))
{
rdU64 = DocFileFormat::FormatUtils::BytesToUInt64(m_Data, m_Position, m_Size);
m_Position += 8;
@ -73,7 +73,7 @@ unsigned short MemoryStream::ReadUInt16()
{
unsigned short rdUShort = 0;
if (m_Data)
if (m_Data && (m_Position + sizeof(unsigned short) <= m_Size))
{
rdUShort = DocFileFormat::FormatUtils::BytesToUInt16 (m_Data, m_Position, m_Size);
m_Position += 2;
@ -93,7 +93,7 @@ short MemoryStream::ReadInt16()
{
short rdShort = 0;
if (m_Data)
if (m_Data && (m_Position + sizeof(short) <= m_Size))
{
rdShort = DocFileFormat::FormatUtils::BytesToInt16 (m_Data, m_Position, m_Size);
m_Position += 2;
@ -106,7 +106,7 @@ int MemoryStream::ReadInt32()
{
int rdInt = 0;
if (m_Data)
if (m_Data && (m_Position + sizeof(_INT32) <= m_Size))
{
rdInt = DocFileFormat::FormatUtils::BytesToInt32 (m_Data, m_Position, m_Size);
m_Position += 4;

View File

@ -181,7 +181,7 @@ namespace OOX
void Diagram::CAnimLvl::toPPTY(NSBinPptxRW::CBinaryFileWriter* pWriter) const
{
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : 0, pWriter);
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : SimpleTypes::EAnimLvlStr::animLvlStr_none, pWriter);
}
//------------------------------------------------------------------------------------------------------
@ -211,7 +211,7 @@ namespace OOX
void Diagram::CAnimOne::toPPTY(NSBinPptxRW::CBinaryFileWriter* pWriter) const
{
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : 0, pWriter);
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : SimpleTypes::EAnimOneStr::animOneStr_none, pWriter);
}
//------------------------------------------------------------------------------------------------------
@ -241,7 +241,7 @@ namespace OOX
void Diagram::CBulletEnabled::toPPTY(NSBinPptxRW::CBinaryFileWriter* pWriter) const
{
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : 0, pWriter);
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : SimpleTypes::onoffFalse, pWriter);
}
//------------------------------------------------------------------------------------------------------
@ -331,7 +331,7 @@ namespace OOX
void Diagram::CDirection::toPPTY(NSBinPptxRW::CBinaryFileWriter* pWriter) const
{
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : 0, pWriter);
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : SimpleTypes::EDirectionDraw::direction_norm, pWriter);
}
//------------------------------------------------------------------------------------------------------
@ -360,7 +360,7 @@ namespace OOX
void Diagram::CHierBranch::toPPTY(NSBinPptxRW::CBinaryFileWriter* pWriter) const
{
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : 0, pWriter);
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : SimpleTypes::EHierBranch::hierBranch_std, pWriter);
}
//------------------------------------------------------------------------------------------------------
@ -390,7 +390,7 @@ namespace OOX
void Diagram::COrgChart::toPPTY(NSBinPptxRW::CBinaryFileWriter* pWriter) const
{
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : 0, pWriter);
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : SimpleTypes::EOnOff::onoffFalse, pWriter);
}
//------------------------------------------------------------------------------------------------------
@ -420,7 +420,7 @@ namespace OOX
void Diagram::CResizeHandles::toPPTY(NSBinPptxRW::CBinaryFileWriter* pWriter) const
{
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : 0, pWriter);
WriteByteToPPTY(m_oVal.IsInit() ? (BYTE)m_oVal->GetValue() : SimpleTypes::EResizeHandles::resizeHandles_exact, pWriter);
}
//------------------------------------------------------------------------------------------------------

View File

@ -2675,7 +2675,12 @@ void CDrawingConverter::ConvertShape(PPTX::Logic::SpTreeElem *elem, XmlUtils::CX
}
else
{
if (pPPTShape->m_eType == PPTShapes::sptCTextBox)
if (pPPTShape->m_eType == PPTShapes::sptCTextBox ||
pPPTShape->m_eType == PPTShapes::sptCRect ||
pPPTShape->m_eType == PPTShapes::sptCRoundRect ||
pPPTShape->m_eType == PPTShapes::sptCWedgeRectCallout ||
pPPTShape->m_eType == PPTShapes::sptCWedgeRoundRectCallout)
// sptCRound1Rect ?
{
pShape->oTextBoxBodyPr->lIns = 91440;
pShape->oTextBoxBodyPr->tIns = 45720;

View File

@ -55,7 +55,7 @@ static const _shape_converter _OO_OOX_custom_shapes[]=
{L"star4" ,L"star4" ,1 ,0 ,50000 },
{L"star5" ,L"star5" ,0 ,0 ,50000 },//??? 19098 неверно
{L"star8" ,L"star8" ,0 ,0 ,50000 },
{L"star24" ,L"star24" ,1 ,0 ,50000 },
{L"star24" ,L"star24" ,0 ,0 ,50000 },
{L"star6" ,L"star6" ,0 ,0 ,50000 },
{L"star12" ,L"star12" ,1 ,0 ,50000 },
{L"round-rectangle" ,L"roundRect" ,0 ,0 ,0 },

View File

@ -477,8 +477,10 @@ void pptx_slide_context::add_background(_oox_fill & fill)
impl_->background_fill_ = fill;
}
void pptx_slide_context::set_name(std::wstring const & name)
void pptx_slide_context::set_name(std::wstring name)
{
boost::replace_all(name, L"&", L"&amp;");
impl_->object_description_.name_ = name;
}

View File

@ -66,7 +66,7 @@ public:
void set_scale (double cx_pt, double cy_pt);
void set_rotate (double angle, bool translate = false);
void set_name (std::wstring const & name);
void set_name (std::wstring name);
void set_id (std::wstring const & id);
void set_anchor (std::wstring anchor, double x_pt, double y_pt);
void set_property (odf_reader::_property p);

View File

@ -372,6 +372,7 @@ void oox_serialize_tcPr(std::wostream & strm, std::vector<const odf_reader::styl
if (instances.size() > 0)
{
odf_reader::style_table_cell_properties_attlist style_cell_attlist = odf_reader::calc_table_cell_properties(instances);
odf_reader::graphic_format_properties_ptr graphic_props = odf_reader::calc_graphic_properties_content(instances);
if (style_cell_attlist.style_vertical_align_)
{
@ -395,6 +396,14 @@ void oox_serialize_tcPr(std::wostream & strm, std::vector<const odf_reader::styl
CP_XML_ATTR(L"marL", (long)padding);
CP_XML_ATTR(L"marR", (long)padding);
}
else if (graphic_props && graphic_props->common_padding_attlist_.fo_padding_)
{
double padding = graphic_props->common_padding_attlist_.fo_padding_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marT", (long)padding);
CP_XML_ATTR(L"marB", (long)padding);
CP_XML_ATTR(L"marL", (long)padding);
CP_XML_ATTR(L"marR", (long)padding);
}
else
{
if (style_cell_attlist.common_padding_attlist_.fo_padding_top_)
@ -402,21 +411,44 @@ void oox_serialize_tcPr(std::wostream & strm, std::vector<const odf_reader::styl
double padding = style_cell_attlist.common_padding_attlist_.fo_padding_top_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marT", (long)padding);
}
else if (graphic_props && graphic_props->common_padding_attlist_.fo_padding_top_)
{
double padding = graphic_props->common_padding_attlist_.fo_padding_top_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marT", (long)padding);
}
if (style_cell_attlist.common_padding_attlist_.fo_padding_bottom_)
{
double padding = style_cell_attlist.common_padding_attlist_.fo_padding_bottom_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marB", (long)padding);
}
else if (graphic_props && graphic_props->common_padding_attlist_.fo_padding_bottom_)
{
double padding = graphic_props->common_padding_attlist_.fo_padding_bottom_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marB", (long)padding);
}
if (style_cell_attlist.common_padding_attlist_.fo_padding_left_)
{
double padding = style_cell_attlist.common_padding_attlist_.fo_padding_left_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marL", (long)padding);
}
else if (graphic_props && graphic_props->common_padding_attlist_.fo_padding_left_)
{
double padding = graphic_props->common_padding_attlist_.fo_padding_left_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marL", (long)padding);
}
if (style_cell_attlist.common_padding_attlist_.fo_padding_right_)
{
double padding = style_cell_attlist.common_padding_attlist_.fo_padding_right_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marR", (long)padding);
}
else if (graphic_props && graphic_props->common_padding_attlist_.fo_padding_right_)
{
double padding = graphic_props->common_padding_attlist_.fo_padding_right_->get_value_unit(odf_types::length::emu);
CP_XML_ATTR(L"marR", (long)padding);
}
}
//vert //
//style_cell_attlist.pptx_serialize(Context, CP_XML_STREAM()); //nodes
@ -437,8 +469,6 @@ void oox_serialize_tcPr(std::wostream & strm, std::vector<const odf_reader::styl
//диагональных в оо нет.
////////////////////////////////////////////////////////////////////////////////////////////////
oox::_oox_fill fill;
odf_reader::graphic_format_properties_ptr graphic_props = odf_reader::calc_graphic_properties_content(instances);
if (graphic_props)
{

View File

@ -868,11 +868,11 @@ static std::wstring convert_href(oox::pptx_conversion_context& Context, const st
if (result == page_names[i])
{
result = std::wstring(L"slide") + std::to_wstring(i + 1) + std::wstring(L".xml");
break;
return result;
}
}
return result;
return std::wstring();
}
void a::pptx_convert(oox::pptx_conversion_context & Context)
@ -887,9 +887,9 @@ void a::pptx_convert(oox::pptx_conversion_context & Context)
if (boost::algorithm::starts_with(href, L"#"))
{
Context.get_text_context().set_action(L"ppaction://hlinksldjump");
href = convert_href(Context, href);
if(!href.empty())
Context.get_text_context().set_action(L"ppaction://hlinksldjump");
}
std::wstring hId = Context.get_slide_context().add_hyperlink(href);

View File

@ -74,12 +74,19 @@ text_list_style::text_list_style(const text_list_style& other)
for (auto& val : other.content_)
{
text_list_level_style_number* ptr = dynamic_cast<text_list_level_style_number*>(val.get());
if(!ptr)
continue;
text_list_level_style_number* style_number_ptr = dynamic_cast<text_list_level_style_number*>(val.get());
text_list_level_style_bullet* style_bullet_ptr = dynamic_cast<text_list_level_style_bullet*>(val.get());
boost::shared_ptr<text_list_level_style_number> style_num = boost::make_shared<text_list_level_style_number>(*ptr);
content_.push_back(style_num);
if (style_number_ptr)
{
boost::shared_ptr<text_list_level_style_number> style_number = boost::make_shared<text_list_level_style_number>(*style_number_ptr);
content_.push_back(style_number);
}
else if (style_bullet_ptr)
{
boost::shared_ptr<text_list_level_style_bullet> style_bullet = boost::make_shared<text_list_level_style_bullet>(*style_bullet_ptr);
content_.push_back(style_bullet);
}
}
}
@ -155,6 +162,14 @@ void text_list_level_style_bullet_attr::add_attributes( const xml::attributes_wc
CP_APPLY_ATTR(L"text:bullet-relative-size", text_bullet_relative_size_);
}
void text_list_level_style_bullet_attr::apply_from(const text_list_level_style_bullet_attr& Other)
{
_CP_APPLY_PROP2(text_style_name_);
_CP_APPLY_PROP2(text_bullet_char_);
common_num_format_prefix_suffix_attlist_.apply_from(Other.common_num_format_prefix_suffix_attlist_);
_CP_APPLY_PROP2(text_bullet_relative_size_);
}
// text_list_level_style_image_attr
//////////////////////////////////////////////////////////////////////////////////////////////////
@ -290,6 +305,12 @@ void style_list_level_label_alignment::add_child_element( xml::sax * Reader, con
const wchar_t * text_list_level_style_bullet::ns = L"text";
const wchar_t * text_list_level_style_bullet::name = L"list-level-style-bullet";
text_list_level_style_bullet::text_list_level_style_bullet(const text_list_level_style_bullet& other)
{
text_list_level_style_attr_.apply_from(other.text_list_level_style_attr_);
text_list_level_style_bullet_attr_.apply_from(other.text_list_level_style_bullet_attr_);
}
void text_list_level_style_bullet::add_attributes( const xml::attributes_wc_ptr & Attributes )
{
text_list_level_style_attr_.add_attributes(Attributes);
@ -791,8 +812,6 @@ void text_list_level_style_bullet::pptx_convert(oox::pptx_conversion_context & C
}
}
void text_list_level_style_image::docx_convert(oox::docx_conversion_context & Context)
{
if (text_list_level_style_attr_.get_text_level() - 1 > 10)

View File

@ -211,6 +211,8 @@ class text_list_level_style_bullet_attr
public:
void add_attributes( const xml::attributes_wc_ptr & Attributes );
void apply_from(const text_list_level_style_bullet_attr& Other);
private:
_CP_OPT(std::wstring) text_style_name_;
_CP_OPT(std::wstring) text_bullet_char_;
@ -234,6 +236,9 @@ public:
static const ElementType type = typeTextListLevelStyleBullet;
CPDOCCORE_DEFINE_VISITABLE();
text_list_level_style_bullet() = default;
text_list_level_style_bullet(const text_list_level_style_bullet& other);
void docx_convert(oox::docx_conversion_context & Context) ;
void pptx_convert(oox::pptx_conversion_context & Context) ;

View File

@ -880,7 +880,8 @@ void OoxConverter::convert(PPTX::Logic::Shape *oox_shape)
_CP_PTR(cpdoccore::odf_writer::text_format_properties) text_properties = boost::make_shared<cpdoccore::odf_writer::text_format_properties>();
_CP_PTR(cpdoccore::odf_writer::graphic_format_properties) graphic_properties = boost::make_shared<cpdoccore::odf_writer::graphic_format_properties>();
convert(oox_shape->txBody->lstStyle.GetPointer(), 0, paragraph_properties.get(), text_properties.get());
if(oox_shape->txBody.is_init())
convert(oox_shape->txBody->lstStyle.GetPointer(), 0, paragraph_properties.get(), text_properties.get());
if (odf_context()->drawing_context()->placeholder_replacing())
{

View File

@ -1668,7 +1668,8 @@ HRESULT CPdfWriter::AddAnnotField(NSFonts::IApplicationFonts* pAppFonts, CAnnotF
PdfWriter::CPage* pPage = m_pPage;
int nID = oInfo.GetID();
pAnnot = m_pDocument->GetAnnot(nID);
if (nID > 0)
pAnnot = m_pDocument->GetAnnot(nID);
if (pAnnot && pOrigPage && pPage != pOrigPage)
{

View File

@ -867,9 +867,6 @@ std::map<std::wstring, std::wstring> CAnnotFonts::GetFreeTextFont(PDFDoc* pdfDoc
std::map<std::wstring, std::wstring> mRes;
std::map<std::wstring, std::wstring> mFontFreeText = GetAnnotFont(pdfDoc, pFontManager, pFontList, oAnnotRef);
#ifndef BUILDING_WASM_MODULE
return mFontFreeText;
#endif
CFontList* pAppFontList = (CFontList*)pFontManager->GetApplication()->GetList();
for (int i = 0; i < arrRC.size(); ++i)
{

View File

@ -513,14 +513,14 @@ namespace PdfReader
}
else
{
double* dDash = new double[nSize];
for (int nIndex = 0; nIndex < nSize; ++nIndex)
{
pDash[nIndex] = PDFCoordsToMM(pDash[nIndex]);
}
dDash[nIndex] = PDFCoordsToMM(pDash[nIndex]);
m_pRenderer->PenDashPattern(pDash, (long)nSize);
m_pRenderer->PenDashPattern(dDash, (long)nSize);
m_pRenderer->put_PenDashStyle(Aggplus::DashStyleCustom);
m_pRenderer->put_PenDashOffset(PDFCoordsToMM(dStart));
RELEASEARRAYOBJECTS(dDash);
}
if (bOffCopy)
delete[] pDash;