creating pdfs with libharu and vala - pdf

i was wondering if anyone could give me pointers on how to go about creating pdf files dynamically(without having to save the file as a pdf) from the vala language. i heard it can be done with libharu so ive been looking into their documentation but its still kinda hazy for me. does anyone know how to go about...
sending written annotations/text from a UI created with vala, to libharu? and having libharu create a pdf from it?
help would be much appreciated. thanks!

Even if the question is quite old I was in need of something similar...
As nemequ said you need to write a vapi to wrap the library.
This is a minimal one based on libhpdf 2.0.8 (not the latest)
=== Filename: haru.vapi ===
[CCode(cheader_filename="hpdf.h", cprefix="HPDF_")]
namespace HPDF {
[CCode(cname="HPDF_STATUS")]
public struct Status : ulong {
}
[CCode(cname="HPDF_REAL")]
public struct Real : float {
}
[CCode(cname="HPDF_Error_Handler", instance_pos = -1)]
public delegate void ErrorHandler (Status error_no, Status detail_no);
[Compact]
[CCode(free_function="HPDF_Free", cname="HPDF_Doc")]
public class Doc {
[CCode(cname="HPDF_New", instance_pos = -1)]
public Doc (ErrorHandler error_handler);
[CCode(cname="HPDF_AddPage")]
public unowned Page add_page();
[CCode(cname="HPDF_GetFont")]
public unowned Font get_font(string name, string? encoding = null);
[CCode(cname="HPDF_SaveToFile")]
public Status save_to_file (string file);
}
[Compact]
[CCode(cname="HPDF_Page")]
public class Page {
[CCode(cname="HPDF_Page_SetFontAndSize")]
public Status set_font_and_size (Font font, float size);
[CCode(cname="HPDF_Page_BeginText")]
public Status begin_text ();
[CCode(cname="HPDF_Page_EndText")]
public Status end_text ();
[CCode(cname="HPDF_Page_TextOut")]
public Status text_out (Real x, Real y, string chars);
[CCode(cname="HPDF_Page_SetCharSpace")]
public Status set_char_space (Real value);
[CCode(cname="HPDF_Page_SetWordSpace")]
public Status set_word_space (Real value);
}
[Compact]
[CCode(cname="HPDF_Font")]
public class Font {
}
}
Then you can consume it from vala.
=== Filename: text_demo.vala ===
using HPDF;
public class Demos.TextDemo {
private void error_handler (Status error_no, Status detail_no) {
stderr.printf("Error %d - detail %d\n", (int)error_no, (int)detail_no);
}
public void run (string filename) {
string samp_text2 = "The quick brown fox jumps over the lazy dog.";
Doc pdf = new Doc(this.error_handler);
unowned Page page = pdf.add_page ();
unowned Font font;
font = pdf.get_font ("Helvetica");
page.set_font_and_size (font, 24);
/* char-spacing 0 */
page.begin_text ();
page.text_out (60, 140, samp_text2);
page.end_text ();
/* char-spacing 1.5 */
page.set_char_space (1.5f);
page.begin_text ();
page.text_out (60, 100, samp_text2);
page.end_text ();
/* char-spacing 1.5, word-spacing 3.5 */
page.set_word_space (2.5f);
page.begin_text ();
page.text_out (60, 60, samp_text2);
page.end_text ();
/* save the document to a file */
stderr.printf("Writing pdf to: %s\n", filename);
pdf.save_to_file (filename);
}
}
public static int main(string[] args) {
new Demos.TextDemo().run (args[1]);
return 0;
}
To compile (tried on windows you'll need to tweak the paths):
valac -C --save-temps text_demo.vala --vapidir . --pkg haru
gcc -g -o text_demo.exe text_demo.c -I ./libharu-2.0.8/include -L
libharu-2.0.8 -l libhpdf
-mms-bitfields -IC:/Src/Tools/opt/include/glib-2.0 -IC:/Src/Tools/opt/lib/glib-2.0/include -LC:/Src/Tools/opt/lib -lglib-2.0 -lintl -lgobject-2.0
And to run:
text_demo.exe test.pdf

Related

Undefined Reference errors when using IL2CPP in Unity

after switching unity scripting to IL2CPP scripting my android build is gettting a lot of undefined reference errors. A lot of them reference to IOS ARKit related stuff. Can i use #if !UNITY_IOS statements to remove them from my android build ? and where can i put these #if statements ?
errors are realated to Bulk_Assembly-CSharp_8.cpp.. i tried putting #if statements in it for platform specific build but does not seem to make a difference
if !UNITY_IOS
public class ARFaceAnchor
{
private UnityARFaceAnchorData faceAnchorData;
private static Dictionary<string, float> blendshapesDictionary;
public ARFaceAnchor (UnityARFaceAnchorData ufad)
{
faceAnchorData = ufad;
if (blendshapesDictionary == null) {
blendshapesDictionary = new Dictionary<string, float> ();
}
}
public string identifierStr { get { return faceAnchorData.identifierStr; } }
public Matrix4x4 transform {
get {
Matrix4x4 matrix = new Matrix4x4 ();
matrix.SetColumn (0, faceAnchorData.transform.column0);
matrix.SetColumn (1, faceAnchorData.transform.column1);
matrix.SetColumn (2, faceAnchorData.transform.column2);
matrix.SetColumn (3, faceAnchorData.transform.column3);
return matrix;
}
}
public ARFaceGeometry faceGeometry { get { return new ARFaceGeometry (faceAnchorData.faceGeometry); } }
public Dictionary<string, float> blendShapes { get { return GetBlendShapesFromNative(faceAnchorData.blendShapes); } }
delegate void DictionaryVisitorHandler(IntPtr keyPtr, float value);
[DllImport("__Internal")]
private static extern void GetBlendShapesInfo(IntPtr ptrDic, DictionaryVisitorHandler handler);
Dictionary<string, float> GetBlendShapesFromNative(IntPtr blendShapesPtr)
{
blendshapesDictionary.Clear ();
GetBlendShapesInfo (blendShapesPtr, AddElementToManagedDictionary);
return blendshapesDictionary;
}
[MonoPInvokeCallback(typeof(DictionaryVisitorHandler))]
static void AddElementToManagedDictionary(IntPtr keyPtr, float value)
{
string key = Marshal.PtrToStringAuto(keyPtr);
blendshapesDictionary.Add(key, value);
}
}
endif
If you want to remove from Android build, use
#if !UNITY_ANDROID
// your code here
#endif
Will be more helpful if you can post your error message is pertaining to which line.
Thanks Darren,
i must have got it all wrong. so
if !UNITY_ANDROID means if NOT Android ?

How to set variable inside of a Coroutine after yielding a webrequest

Okay I will try and explain this to the best of my ability. I have searched and searched all day for a solution to this issue but can't seem to find it. The problem that I am having is that I have a list of scriptable objects that I am basically using for custom properties to create gameobjects off of. One of those properties that I need to get is a Texture2D that I turn into a sprite. Therefor, I am using UnityWebRequest in a Coroutine and am having to yield the response. After I get the response I am trying to set the variable. However even using Lambdas it seems to me that if I yield return the response before the result it will not set the variable. So every time I check the variable after the Coroutine it comes back null. If someone could enlighten me with what I am missing here that would be just great!
Here is the Scriptable Object Class I am using.
[CreateAssetMenu(fileName = "new movie",menuName = "movie")]
public class MovieTemplate : ScriptableObject
{
public string Title;
public string Description;
public string ImgURL;
public string mainURL;
public string secondaryURL;
public Sprite thumbnail;
}
Here is the call to the Coroutine
foreach (var item in nodes)
{
templates.Add(GetMovieData(item));
}
foreach (MovieTemplate movie in templates)
{
StartCoroutine(GetMovieImage(movie.ImgURL, result =>
{
movie.thumbnail = result;
}));
}
Here is the Coroutine itself
IEnumerator GetMovieImage(string url, System.Action<Sprite> result)
{
using (UnityWebRequest web = UnityWebRequestTexture.GetTexture(url))
{
yield return web.SendWebRequest();
var img = DownloadHandlerTexture.GetContent(web);
result(Sprite.Create(img, new Rect(0, 0, img.width, img.height), Vector2.zero));
}
}
From what you desribe it still seems that the texture is somehow disposed as soon as the routine finishes. My guess would be that it happens due to the using block.
I would store the original texture reference
[CreateAssetMenu(fileName = "new movie",menuName = "movie")]
public class MovieTemplate : ScriptableObject
{
public string Title;
public string Description;
public string ImgURL;
public string mainURL;
public string secondaryURL;
public Sprite thumbnail;
public Texture texture;
public void SetSprite(Sprite newSprite, Texture newTexture)
{
if(texture) Destroy(texture);
texture = newTexture;
var tex = (Texture2D) texture;
thumbnail = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
}
}
So you can keep track of the texture itself as well, let it not be collected by the GC but also destroy it when not needed anymore. Usually Texture2D is removed by the GC as soon as there is no reference to it anymore but Texture2D created by UnityWebRequest might behave different.
Than in the webrequest return the texture and don't use using
IEnumerator GetMovieImage(string url, System.Action<Texture> result)
{
UnityWebRequest web = UnityWebRequestTexture.GetTexture(url));
yield return web.SendWebRequest();
if(!web.error)
{
result?.Invoke(DownloadHandlerTexture.GetContent(web));
}
else
{
Debug.LogErrorFormat(this, "Download error: {0} - {1}", web.responseCode, web.error);
}
}
and finally use it like
for (int i = 0; i < templates.Count; i++)
{
int index = i;//If u use i, it will be overriden too so we make a copy of it
StartCoroutine(
GetMovieImage(
templates[index].ImgURL,
result =>
{
templates[index].SetSprite(result);
})
);
}
The problem is with this section of your code :
foreach (MovieTemplate movie in templates)
{
StartCoroutine(GetMovieImage(movie.ImgURL, result =>
{
movie.thumbnail = result;//wrong movie obj
}));
}
Here you will loose refrence to movie object(override by foreach) before the result of callback arrive .
Change it to something like this :
foreach (int i=0;i<templates.Length;i++)
{
int index= i;//If u use i, it will be overriden too so we make a copy of it
StartCoroutine(GetMovieImage(movie.ImgURL, result =>
{
templates[index].thumbnail = result;
}));
}

How to replace / remove text from a PDF file

How would I go about replacing / removing text from a PDF file?
I have a PDF file that I obtained somewhere, and I want to be able to replace some text within it.
Or, I have a PDF file that I want to obscure (redact) some of the text within it so that it's no longer visible [and so that it looks cool, like the CIA files].
Or, I have a PDF that contains global Javascript that I want to stop from interrupting my use of the PDF.
This is possible in a limited fashion with the use of iText / iTextSharp.
It will only work with Tj/TJ opcodes (i.e. standard text, not text embedded in images, or drawn with shapes).
You need to override the default PdfContentStreamProcessor to act on the page content streams, as presented by Mkl here Removing Watermark from PDF iTextSharp. Inherit from this class, and in your new class look for the Tj/TJ opcodes, the operand(s) will generally be the text element(s) (for a TJ this may not be straightforward text, and may require further parsing of all the operands).
A pretty basic example of some of the flexibility around iTextSharp is available from this github repository https://github.com/bevanweiss/PdfEditor (code excerpts below also)
NOTE: This utilises the AGPL version of iTextSharp (and is hence also AGPL), so if you will be distributing executables derived from this code or allowing others to interact with those executables in any way then you must also provide your modified source code. There is also no warranty, implied or expressed, related to this code. Use at your own peril.
PdfContentStreamEditor
using System.Collections.Generic;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace PDFCleaner
{
public class PdfContentStreamEditor : PdfContentStreamProcessor
{
/**
* This method edits the immediate contents of a page, i.e. its content stream.
* It explicitly does not descent into form xobjects, patterns, or annotations.
*/
public void EditPage(PdfStamper pdfStamper, int pageNum)
{
var pdfReader = pdfStamper.Reader;
var page = pdfReader.GetPageN(pageNum);
var pageContentInput = ContentByteUtils.GetContentBytesForPage(pdfReader, pageNum);
page.Remove(PdfName.CONTENTS);
EditContent(pageContentInput, page.GetAsDict(PdfName.RESOURCES), pdfStamper.GetUnderContent(pageNum));
}
/**
* This method processes the content bytes and outputs to the given canvas.
* It explicitly does not descent into form xobjects, patterns, or annotations.
*/
public virtual void EditContent(byte[] contentBytes, PdfDictionary resources, PdfContentByte canvas)
{
this.Canvas = canvas;
ProcessContent(contentBytes, resources);
this.Canvas = null;
}
/**
* This method writes content stream operations to the target canvas. The default
* implementation writes them as they come, so it essentially generates identical
* copies of the original instructions the {#link ContentOperatorWrapper} instances
* forward to it.
*
* Override this method to achieve some fancy editing effect.
*/
protected virtual void Write(PdfContentStreamProcessor processor, PdfLiteral operatorLit, List<PdfObject> operands)
{
var index = 0;
foreach (var pdfObject in operands)
{
pdfObject.ToPdf(null, Canvas.InternalBuffer);
Canvas.InternalBuffer.Append(operands.Count > ++index ? (byte) ' ' : (byte) '\n');
}
}
//
// constructor giving the parent a dummy listener to talk to
//
public PdfContentStreamEditor() : base(new DummyRenderListener())
{
}
//
// constructor giving the parent a dummy listener to talk to
//
public PdfContentStreamEditor(IRenderListener renderListener) : base(renderListener)
{
}
//
// Overrides of PdfContentStreamProcessor methods
//
public override IContentOperator RegisterContentOperator(string operatorString, IContentOperator newOperator)
{
var wrapper = new ContentOperatorWrapper();
wrapper.SetOriginalOperator(newOperator);
var formerOperator = base.RegisterContentOperator(operatorString, wrapper);
return (formerOperator is ContentOperatorWrapper operatorWrapper ? operatorWrapper.GetOriginalOperator() : formerOperator);
}
public override void ProcessContent(byte[] contentBytes, PdfDictionary resources)
{
this.Resources = resources;
base.ProcessContent(contentBytes, resources);
this.Resources = null;
}
//
// members holding the output canvas and the resources
//
protected PdfContentByte Canvas = null;
protected PdfDictionary Resources = null;
//
// A content operator class to wrap all content operators to forward the invocation to the editor
//
class ContentOperatorWrapper : IContentOperator
{
public IContentOperator GetOriginalOperator()
{
return _originalOperator;
}
public void SetOriginalOperator(IContentOperator op)
{
this._originalOperator = op;
}
public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List<PdfObject> operands)
{
if (_originalOperator != null && !"Do".Equals(oper.ToString()))
{
_originalOperator.Invoke(processor, oper, operands);
}
((PdfContentStreamEditor)processor).Write(processor, oper, operands);
}
private IContentOperator _originalOperator = null;
}
//
// A dummy render listener to give to the underlying content stream processor to feed events to
//
class DummyRenderListener : IRenderListener
{
public void BeginTextBlock() { }
public void RenderText(TextRenderInfo renderInfo) { }
public void EndTextBlock() { }
public void RenderImage(ImageRenderInfo renderInfo) { }
}
}
}
TextReplaceStreamEditor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace PDFCleaner
{
public class TextReplaceStreamEditor : PdfContentStreamEditor
{
public TextReplaceStreamEditor(string MatchPattern, string ReplacePattern)
{
_matchPattern = MatchPattern;
_replacePattern = ReplacePattern;
}
private string _matchPattern;
private string _replacePattern;
protected override void Write(PdfContentStreamProcessor processor, PdfLiteral oper, List<PdfObject> operands)
{
var operatorString = oper.ToString();
if ("Tj".Equals(operatorString) || "TJ".Equals(operatorString))
{
for(var i = 0; i < operands.Count; i++)
{
if(!operands[i].IsString())
continue;
var text = operands[i].ToString();
if(Regex.IsMatch(text, _matchPattern))
{
operands[i] = new PdfString(Regex.Replace(text, _matchPattern, _replacePattern));
}
}
}
base.Write(processor, oper, operands);
}
}
}
TextRedactStreamEditor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace PDFCleaner
{
public class TextRedactStreamEditor : PdfContentStreamEditor
{
public TextRedactStreamEditor(string MatchPattern) : base(new RedactRenderListener(MatchPattern))
{
_matchPattern = MatchPattern;
}
private string _matchPattern;
protected override void Write(PdfContentStreamProcessor processor, PdfLiteral oper, List<PdfObject> operands)
{
base.Write(processor, oper, operands);
}
public override void EditContent(byte[] contentBytes, PdfDictionary resources, PdfContentByte canvas)
{
((RedactRenderListener)base.RenderListener).SetCanvas(canvas);
base.EditContent(contentBytes, resources, canvas);
}
}
//
// A pretty simple render listener, all we care about it text stuff.
// We listen out for text blocks, look for our text, and then put a
// black box over it.. text 'redacted'
//
class RedactRenderListener : IRenderListener
{
private PdfContentByte _canvas;
private string _matchPattern;
public RedactRenderListener(string MatchPattern)
{
_matchPattern = MatchPattern;
}
public RedactRenderListener(PdfContentByte Canvas, string MatchPattern)
{
_canvas = Canvas;
_matchPattern = MatchPattern;
}
public void SetCanvas(PdfContentByte Canvas)
{
_canvas = Canvas;
}
public void BeginTextBlock() { }
public void RenderText(TextRenderInfo renderInfo)
{
var text = renderInfo.GetText();
var match = Regex.Match(text, _matchPattern);
if(match.Success)
{
var p1 = renderInfo.GetCharacterRenderInfos()[match.Index].GetAscentLine().GetStartPoint();
var p2 = renderInfo.GetCharacterRenderInfos()[match.Index+match.Length].GetAscentLine().GetEndPoint();
var p3 = renderInfo.GetCharacterRenderInfos()[match.Index+match.Length].GetDescentLine().GetEndPoint();
var p4 = renderInfo.GetCharacterRenderInfos()[match.Index].GetDescentLine().GetStartPoint();
_canvas.SaveState();
_canvas.SetColorStroke(BaseColor.BLACK);
_canvas.SetColorFill(BaseColor.BLACK);
_canvas.MoveTo(p1[Vector.I1], p1[Vector.I2]);
_canvas.LineTo(p2[Vector.I1], p2[Vector.I2]);
_canvas.LineTo(p3[Vector.I1], p3[Vector.I2]);
_canvas.LineTo(p4[Vector.I1], p4[Vector.I2]);
_canvas.ClosePathFillStroke();
_canvas.RestoreState();
}
}
public void EndTextBlock() { }
public void RenderImage(ImageRenderInfo renderInfo) { }
}
}
Using them with iTextSharp
var reader = new PdfReader("SRC FILE PATH GOES HERE");
var dstFile = File.Open("DST FILE PATH GOES HERE", FileMode.Create);
pdfStamper = new PdfStamper(reader, output, reader.PdfVersion, false);
// We don't need to auto-rotate, as the PdfContentStreamEditor will already deal with pre-rotated space..
// if we enable this we will inadvertently rotate the content.
pdfStamper.RotateContents = false;
// This is for the Text Replace
var replaceTextProcessor = new TextReplaceStreamEditor(
"TEXT TO REPLACE HERE",
"TEXT TO SUBSTITUTE IN HERE");
for(int i=1; i <= reader.NumberOfPages; i++)
replaceTextProcessor.EditPage(pdfStamper, i);
// This is for the Text Redact
var redactTextProcessor = new TextRedactStreamEditor(
"TEXT TO REDACT HERE");
for(int i=1; i <= reader.NumberOfPages; i++)
redactTextProcessor.EditPage(pdfStamper, i);
// Since our redacting just puts a box over the top, we should secure the document a bit... just to prevent people copying/pasting the text behind the box.. we also prevent text to speech processing of the file, otherwise the 'hidden' text will be spoken
pdfStamper.Writer.SetEncryption(null,
Encoding.UTF8.GetBytes("ownerPassword"),
PdfWriter.AllowDegradedPrinting | PdfWriter.AllowPrinting,
PdfWriter.ENCRYPTION_AES_256);
// hey, lets get rid of Javascript too, because it's annoying
pdfStamper.Javascript = "";
// and then finally we close our files (saving it in the process)
pdfStamper.Close();
reader.Close();
You can use GroupDocs.Redaction (available for .NET) for replacing or removing the text from PDF documents. You can perform the exact phrase, case-sensitive and regular expression redaction (removal) of the text. The following code snippet replaces the word "candy" with "[redacted]" in the loaded PDF document.
C#:
using (Document doc = Redactor.Load("D:\\candy.pdf"))
{
doc.RedactWith(new ExactPhraseRedaction("candy", new ReplacementOptions("[redacted]")));
// Save the document to "*_Redacted.*" file.
doc.Save(new SaveOptions() { AddSuffix = true, RasterizeToPDF = false });
}
Disclosure: I work as Developer Evangelist at GroupDocs.

Making a highly customizable method, or a specific method that does a task?

I'm not really sure how I would phrase the title right, so I apologize for the initial confusion.
This is just a small question I had about how to structure code and such and I have no idea on what to call it so I will explain it with this example:
Say I am writing a Call of Duty type game where the player can customize their weapons with certain attachment.
I have a class that defines each gun. It looks something like this:
class Gun {
int clip = 30;
int ammo = 100;
float reloadTime = 5f;
float damage = 10f;
Attachment[] attachments;
//Plus some not included attachments.
void shoot() {
//...
}
void reload() {
//...
}
void applyAllAttachments() {
//Apply the list of attachments' effects
}
}
class Attachment {
void effect() {
//change the gun in some way.
}
}
Now I would like to add 4 attachments, Fast Mags (increase reload speed), Hollow Point (increase damage), Grenade Launcher (Secondary Gun) and Minigun (Replace the barrel with a minigun or something).
For the Fast Mags and the Hollow Point, it should be simple, all I have to do is change a number or a value, but for the Grenade Launcher and Minigun, which have custom, extra functions (like Unity Delegates), would it be wiser to add a function that handles external custom firing types, or would it be better to just have separate methods inside the Gun class that specifically handle to extra minigun functions?
TL;DR
If I want to add a grenade launcher attachment to a gun, should I do this:
class Gun {
int clip = 30;
int ammo = 100;
float reloadTime = 5f;
float damage = 10f;
Attachment[] attachments = Attachment[10];
//Plus some not included attachments.
void shoot() {
//...
customShoot();
}
void customShoot() {
//Apply attachments custom attachment shoot methods.
}
void reload() {
//...
}
void applyAllAttachments() {
//Apply the list of attachments' effects
}
}
class GrenadeLauncher extends Attachment {
#Override
public void effect() {
//Spawn new grenade
}
}
Or This:
class Gun {
int clip = 30;
int ammo = 100;
float reloadTime = 5f;
float damage = 10f;
Attachment[] attachments = Attachment[10];
//Plus some not included attachments.
void shoot() {
//...
if (attachments.GetType() == GrenadeLauncher) {
grenadeLauncherShoot();
}
}
void grenadeLauncherShoot() {
}
void reload() {
//...
}
void applyAllAttachments() {
//Apply the list of attachments' effects
}
}
Sorry for my pseudo/java code, hope it's comprehensible.
The first way is better: You can create new attachments without having to modify the Gun class.
In a general manner, you shouldn't need to check for type, and your code will be cleaner if you don't.
Here, your Attachment class should be abstract (I suppose it already is), and force children to implements some functions.
public abstract class Attachment
{
protected abstract void shoot();
}
Then the gun calls it for all Attachements:
class Gun {
int clip = 30;
int ammo = 100;
float reloadTime = 5f;
float damage = 10f;
Attachment[] attachments = Attachment[10];
//Plus some not included attachments.
void shoot() {
//...
for(int i = 0; i < attachments.length(); ++i) {
attachments[i].shoot();
}
}
void reload() {
//...
}
}
class GrenadeLauncher extends Attachment {
#Override
public void shoot()
{
//Spawn new grenade
}
}
By the way, why did you tag java and Unity? If you work with unity your code should be c# or javascript

Why are my screenshots only black?

could someone tell me why my screenshots are only black? I am still learning and couldnt find a clue why they are only black.
This is my Utility class
static class XNAUtilities
{
private static RenderTarget2D ssTexture;
private static KeyboardState currentState, previousState;
private static int counter;
public static void TakeScreenShot(GraphicsDevice device, Keys theKey)
{
// Take Screenshot
currentState = Keyboard.GetState();
if (currentState.IsKeyDown(theKey) && previousState.IsKeyUp(theKey))
{
//device.SetRenderTarget(null);
PresentationParameters pparameters = device.PresentationParameters;
ssTexture = new RenderTarget2D(device, pparameters.BackBufferWidth, pparameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None); //??
FileStream fileStream = new System.IO.FileStream(#"Screenshot" + "_" + counter + ".png", System.IO.FileMode.CreateNew);
ssTexture.SaveAsPng(fileStream, pparameters.BackBufferWidth, pparameters.BackBufferHeight);
counter++;
}
previousState = currentState;
}
}
}
This is my Update and Draw from Game1.cs
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
myModelRotation += MathHelper.ToRadians(1f);
// Take a Screenshot
XNAUtilities.TakeScreenShot(GraphicsDevice, Keys.F8);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
Matrix[] transforms = new Matrix[myModel.Bones.Count];
myModel.CopyAbsoluteBoneTransformsTo(transforms);
foreach (ModelMesh mesh in myModel.Meshes)
{
foreach (BasicEffect effects in mesh.Effects)
{
effects.EnableDefaultLighting();
effects.World = transforms[mesh.ParentBone.Index]
* Matrix.CreateRotationY(myModelRotation)
* Matrix.CreateTranslation(myModelPosition);
effects.View = Matrix.CreateLookAt(new Vector3(200, 100, 400), Vector3.Zero, Vector3.Up);
effects.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45f),
GraphicsDevice.Viewport.AspectRatio, 1, 5000);
}
mesh.Draw();
}
smileySprite.DrawSprites(GraphicsDevice, spriteBatch, new Vector2(10,10), Color.White);
base.Draw(gameTime);
}
You're not actually rendering to your render target. So you're saving the blank target.
You need to wrap your scene drawing like so:
GraphicsDevice.SetRenderTarget(ssTexture);
// Render your scene here
GraphicsDevice.SetRenderTarget(null);
// Now you can save your render target as a texture